2017-08-13 85 views
0

是否可以通過異步管道對可觀察類調用方法?是否可以通過異步管道調用類方法

我試過以下,但不能得到它的工作,所以想知道如果這是可能的或可以以更好的方式完成?

app.component.html

<p>Total Cost: {{ (orderState$ | async).TotalPrice() }}</p> 

order.state.ts

export class OrderState { 
    lineItems: OrderLineItem[]; 

    public TotalPrice(): number 
    { 
     // TODO: Calculate price of line items 
     return 199; 
    } 
} 
+0

嘗試此操作的結果是什麼? – 2017-08-13 15:44:28

+0

當然:http://plnkr.co/edit/KNUZvoXCLVeTGTrldPIa?p=preview。如果您發佈了您所嘗試的內容以及錯誤信息,最好將其作爲一個完整的簡單示例,我們可以提供幫助。否則,你的問題的答案是「是」,但我真的想問這個問題。 –

回答

1

創建另一個觀察的,如果它是必要的。最好在subscribe內設置一個變量。

export class OrderState { 
    lineItems: OrderLineItem[]; 
    get totalPrice(): number { 
    // TODO: Calculate price of line items 
    return 199; 
    } 
} 

export class TheComponent { 
    orderState$: Observable<OrderState>; 
    // Here 
    totalPrice$: Observable<string>; 

    constructor() { 
    // And then after you know what the orderState is. 
    this.totalPrice$ = this.orderState$.map(state => state.totalPrice); 
    } 
} 

<p>Total Cost: {{totalPrice$ | async}}</p> 
+0

這正是我需要做的。謝謝。 – Remotec

1

也許這樣的事情可以做的伎倆。 基本上在構造函數中訂閱流,當數據到達時計算價格。

此外,如果你要單元測試,這將比模板中的一切都容易。

app.component.html

<p>Total Cost: {{ totalPrice }}</p> 

order.state.ts

export class OrderState { 
    lineItems: OrderLineItem[]; 
    totalPrice: string = ''; 

    constructor() { 
    orderState$.subscribe((value) => { 
     this.totalPrice = this.CalculateTotalPrice(value); 
    }); 
    } 

    public CalculateTotalPrice(): number { 
    // TODO: Calculate price of line items 
    return 199; 
    } 
} 
1

是的,那是可能的。這裏是updateRenderer function怎麼看起來像由編譯器生成:

function(_ck,_v) { 
    ... 
    var currVal_1 = jit_unwrapValue_7(_v,7,0,jit_nodeValue_8(_v,8).transform(_co.orderState$)).TotalPrice(); 
    _ck(_v,7,0,currVal_1); 
    }); 

讓我們來看看它的計算結果。首先這部分:

jit_nodeValue_8(_v,8).transform(_co.orderState$) 

transform方法訂閱到orderState$觀察到,並返回OrderState實例。然後這一部分:

jit_unwrapValue_7(...) 

unwrapValue函數返回該實例,以及:

export function unwrapValue(view: ViewData, nodeIdx: number, bindingIdx: number, value: any): any { 
    if (value instanceof WrappedValue) { 
     .... 
    } 
    return value; 
} 

所以評估整個表達式的結果:

jit_unwrapValue_7(_v,7,0,jit_nodeValue_8(_v,8).transform(_co.orderState$)) 

OrderState等實例你可以調用任何方法:

jit_unwrapValue_7(...).TotalPrice(); 
+0

Helo,@Maximus!就像你的文章一樣..但是,爲什麼不簡單地用'map'創建一個新的observable,並且使getter而不是method?爲什麼這個代碼難以閱讀?:) –

+0

@LyubimovRoman,我不知道:)。我只是回答了有關Angular表達式功能支持的問題,這是作者問的。這是Angular角度內部的一個答案 –

相關問題