我有一個自定義RxJS主題,代表隨時間變化的距離(製作導航應用程序)。它會隨着時間的推移在不同的地方更新。一個簡化的版本是:Angular 4在模板中顯示自定義RxJS主題
內部服務上面
this.distance$ = new Subject();
// After some event
this.distance$.next(1234)
// After another event
this.distance$.next(1240);
getDistance() {
return this.distance$;
}
似乎工作。當我在組件中編寫下面的代碼時,每當它發生變化時,都會在控制檯中獲取更新。
this.myService.getDistance().subscribe(distance => console.log(distance));
但是,當我嘗試在我的組件模板中顯示它時,它永遠不會更新超出第一個值。
我的部件
this.distance$ = this.myService.getDistance();
我的模板
<p>{{distance$ | async}}</p>
所顯示的值始終等於所述第一發射距離。它永遠不會更新。
在另一個嘗試我在分量從未表現出任何結果都寫了:
this.routeBuilderService.getDistance().subscribe(distance => this.distance = distance);
然後就是包含在模板{{距離}}。
這應該工作。請重現它https://plnkr.co/edit/L2gX2jkThR9fSShNDriI?p=preview – yurzui
感謝您的Plunkr。我的整個代碼在這裏:https://github.com/ErikNijland/routebuilder/tree/master/src/app/components/route和https://github.com/ErikNijland/routebuilder/tree/master/src/app/服務/路由建設者。 它可能與在異步函數內調用next有關嗎?此外,點擊事件不是Angular事件,而是來自Google地圖。 我會嘗試在Plunkr中自己複製它。 –
當您使用Google Maps時,您可以在角度區域之外運行代碼,角度將不會運行更改檢測週期 – yurzui