2016-11-05 5 views
0

私はショッピングカートのアイテムを保持する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; 
     }) 



    } 

} 
+1

は 'async'パイプとそれをチェーン::あなたが好きな場合は、あなたが好きなようにチェーンなど多くのパイプが..あなたは、中括弧を使用することができ

// COMPONENT items: Observable<StoreItem[]>; constructor(private cartService: CartService) { this.items = cartService.cartList$ } // TEMPLATE {{items | async | calculateTotal}} 

' {{項目|非同期| calculateTotal}} '。 – cartant

答えて

0

あなたのプロパティitemsは観測できません。私はあなたのサービスを知らない、それは配列を返すか、あるいはJSONだろうか?それはあなたがその観測可能を購読しようとすることを地元の財産にアイテムを置く。..

されている。..

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

をすべてが右に行けば..

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

を仕事とあなたのパイプを変更する必要があります代わりにその観測可能なものを直接使うことができます! @cartantは既にコメントしていますので、asyncパイプとcalculateTotalパイプを使用してください。

{{((items | async) | calculateTotal) | anyOtherPipe : 'with' : 'three' : 'paramteres'}} 
関連する問題