2016-12-07 61 views
0

嘗試可觀察到的對象的屬性傳遞給組件是這樣的:如何將Observable屬性傳遞給Angular2中的組件?

<bookmark [type]="'store'" [targetId]="(store | async)?.id" [endDate]="99999999999999"></bookmark> 

但目標ID總是不確定的。什麼是正確的方式呢?

+0

你能分享組件代碼嗎?另外,你不需要使用異步和?一起。 –

+0

嘗試使用'[targetId] =「store?.id | async」 –

回答

0

你這樣做是正確的,但我猜你所面對的另一個問題..

讓我在這裏展示它:https://plnkr.co/edit/AE67JyXZ5hg6A1ahrm7E?p=preview

如果這是一個「正常」的觀察到的,認爲將只在更新在視圖啓動後觸發事件!

如果有事件發生,它將不會顯示!

因此,您應該使用BehaviorSubject,這將「緩衝」最後一個值。

@Component({ 
    selector: 'my-app', 
    template: ` 
    <div> 
     <h2>Hello {{name}}</h2> 

     <br /> 
     without timeout: {{ (testWoTimeout | async)?.any }} <!-- will not be shown --> 

     <br /> 
     with timeout: {{ (test | async)?.any }} <!-- will be shown cause of that timeout --> 

     <br /> 
     behavior subject: {{ (behaviorTest | async)?.any }} <!-- will be shown cause of that BehaviorSubject --> 
    </div> 
    `, 
}) 
export class App { 
    name:string; 

    test = new Subject(); 
    testWoTimeout = new Subject(); 
    behaviorTest = new BehaviorSubject({ any: 'default' }); 

    constructor() { 
    this.name = 'Angular2' 
    } 

    ngOnInit() { 

    this.testWoTimeout.next({ any: 'prop' }); // this will not be shown, cause its fired before the view was initiated! 

    this.behaviorTest.next({ any: 'prop' }); 

    setTimeout(() => { 
     this.test.next({ any: 'prop' }); 
    }, 250); 
    } 
} 
相關問題