→ LoveMoon: 回文有文章,請參考 12/27 22:56
https://stackblitz.com/edit/angular-w3njbx
↑上面的程式,我在child1 component中訂閱了service裡的Subject物件,
而在child2 component的按鈕按下後,才會接收到觸發了,而去做後續行為
這個例子中,我預期的就是按鈕每按一次,我就console.log一次,
但是我發現,在路由跳轉的過程中,只要child2 component進入一次
就會連同上次的紀錄都留著,也就是說:
第一次進入child2 component按下按鈕一次,console.log一次(正常)
先按連結離開child2 component
第二次再進入child2 compoent按下按鈕一次,console.log直接跳出兩次結果
先按連結離開child2 component
第三次再進入child2 component按下按鈕一次,console.log直接跳出三次結果
請問為什麼會這樣呢?
------------------------------------------------------------------------
首先感謝LoveMoon大的回應~
由於我另外又不知道哪邊爬到類似這個問題的解答
以這篇的例子來解說:
this.footerService.service$.subscribe(()=>{
console.log('test');
});
訂閱會回傳一個Subscription物件
因此可以設一個變數屬性來接這個訂閱後回傳的物件
this.subscription = this.footerService.service$.subscribe(()=>{
console.log('test');
});
然後在訂閱service的component(Child2 component),的ngOnDestroy週期中取消訂閱
ngOnDestroy(){
this.subscription.unscribe();
}
不知道這方法跟LoveMoon大的差異在哪?
總之都會再找時間好好理解~
※ 編輯: heavenbetula (122.116.61.243), 12/27/2018 21:33:48
※ 編輯: heavenbetula (122.116.61.243), 12/27/2018 21:34:23
大家好~小弟是Angular剛接觸沒多久的新手
最近在使用Service在路由間跳轉時遇到一些問題