【问题标题】:How to use pipe on observable data?如何在可观察数据上使用管道?
【发布时间】:2016-11-05 16:10:18
【问题描述】:

我有一个组件订阅了包含购物车项目的 CartService。我想做的是使用管道根据内容计算购物车总数并显示值。

如何迭代我的可观察数据以计算/返回总数?现在当我注销进入管道的值时,它只是返回可观察数据而不是数据。什么给了?

//calculateTotal.pipe.ts
import { Pipe, PipeTransform } from '@angular/core';

import * as _ from "lodash";

@Pipe({name: 'calculateTotal'})
export class CalculateTotal implements PipeTransform {
  transform(items: string): any {

    _.each(items, function(item){
      console.log(item);
    })

    return items;

  }
}



// nav-cart.component.pug
{{items | calculateTotal}}




//nav-cart.component.ts
import { Component } from '@angular/core';


import { StoreItem } from '../../store.item.interface'
import { CartService } from '../../services/cart.service'


@Component({
  selector: 'nav-cart-component',
  styleUrls:['nav-cart.component.css'],
  templateUrl: 'nav-cart.component.pug',
  encapsulation: ViewEncapsulation.Native  // Use the native Shadow DOM to encapsulate our CSS

})
export class NavCartComponent {

  cartItems:StoreItem[] = [];

  items: StoreItem[] ;
  constructor(private cartService: CartService) {

    cartService.cartList$.subscribe(
      res => {
        this.items = res;
      })



  }

}

【问题讨论】:

  • async 管道链接它:{{ items | async | calculateTotal }}

标签: angular rxjs


【解决方案1】:

您的财产items 不是可观察的。我不知道你的服务,它会返回一个数组,还是它的 JSON?如果一切顺利,它应该可以工作..

cartService.cartList$.subscribe(
   res => {
      console.log(res); // CHECK THIS.. VALID ARRAY?
      this.items = res;
   });

然后改变你的管道..

transform(items: ItemStore[]): any {
   console.log(items); // ARRAY HERE?

您正在尝试订阅该 observable 并将该项目放入本地属性..

你可以直接使用那个 observable! 正如@cartant 已经评论的那样,您应该使用async-pipe,然后使用calculateTotal-pipe。

// COMPONENT

items: Observable<StoreItem[]>;

constructor(private cartService: CartService) {
   this.items = cartService.cartList$
}

// TEMPLATE

{{items | async | calculateTotal}}

你可以链接任意数量的管道。如果你喜欢,你可以使用大括号:

{{((items | async) | calculateTotal) | anyOtherPipe : 'with' : 'three' : 'paramteres'}}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-04
    相关资源
    最近更新 更多