這些進口添加到您的組件
import 'rxjs/add/operator/takeUntil';
import { Subject } from 'rxjs/Subject';
在你的類添加這個 - 我通常做這種構造之上。
private ngUnsubscribe: Subject<any> = new Subject<any>()
添加ngOnDestroy功能
ngOnDestroy() {
this.ngUnsubscribe.next();
this.ngUnsubscribe.complete();
}
,然後添加這立即您.subscribe之前(你應該在每一個部件與.subscribe倍數之前使用這個確切的語法)。
.takeUntil(this.ngUnsubscribe)
所以在你的情況下,它看起來像這樣。
watchMethod(){
this.geolocation.watchPosition()
.takeUntil(this.ngUnsubscribe)
.subscribe(resp => {
let userLatLong = { "lat": resp.coords.latitude, "lng": resp.coords.longitude };
console.log('is watching')
});
}
所以會發生什麼是訂閱將保持活動狀態,直到從組件導航離開,此時ngOnDestroy其從可觀察退訂乾淨火災。
如果你想手動停止不留組件訂閱,你可以這樣做:
stopWatching(){
this.ngUnsubscribe.next();
this.ngUnsubscribe.complete();
}
請注意,您還可以刪除this.watchPosition實例變量,這似乎只是被用作開銷支持.subscribe方法的腳手架。
編輯:我能想到的唯一的事情是按鈕單擊創建多個事件,它導致.subscribe多次觸發。
也許在你的按鈕中,包含$ event作爲參數,然後在你的函數中調用stopPropagation事件。
<button (click)="watchMethod($event)">Watch Method </button>
並更新watchMethod:
watchMethod(event){
event.stopPropagation();
this.geolocation.watchPosition()
.takeUntil(this.ngUnsubscribe)
.subscribe(resp => {
let userLatLong = { "lat": resp.coords.latitude, "lng": resp.coords.longitude };
console.log('is watching')
});
}
你能否擴大* 「沒有工作」 *。錯誤?意外的輸出? – jonrsharpe
這就是問題所在,我沒有收到任何錯誤!沒有輸出。唯一的是我看到'watchMethod()'繼續運行,因爲控制檯打印'正在監視' –
然後*在問題*中提及,這是[mcve]的一部分。你似乎有[問這兩次](https://stackoverflow.com/q/45654369/3001761),只有微小的差異;爲什麼? – jonrsharpe