2017-08-12 109 views
-1

我試圖從事件取消訂閱();然而,它沒有工作,這裏是一個代碼片段:Angular - 無法從事件取消訂閱()

watchMethod(){ 
    this.watchPosition = this.geolocation.watchPosition().subscribe(resp => { 
    let userLatLong = { "lat": resp.coords.latitude, "lng": resp.coords.longitude }; 
    console.log('is watching') 
}); 
} 

stopWatching(){ 
//on click stop watching the current user location 
this.watchPosition.unsubscribe(); 
} 

順便說一句,我沒有得到任何輸出,也沒有錯誤。我在控制檯上看到的唯一一件事是:is watching由於某種原因,unsubscribe()不起作用。

有什麼想法可能是錯的?

+1

你能否擴大* 「沒有工作」 *。錯誤?意外的輸出? – jonrsharpe

+0

這就是問題所在,我沒有收到任何錯誤!沒有輸出。唯一的是我看到'watchMethod()'繼續運行,因爲控制檯打印'正在監視' –

+0

然後*在問題*中提及,這是[mcve]的一部分。你似乎有[問這兩次](https://stackoverflow.com/q/45654369/3001761),只有微小的差異;爲什麼? – jonrsharpe

回答

-1

這些進口添加到您的組件

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') 
     }); 
    } 
+0

您可以擴展爲什麼 - 這比取消訂閱更好嗎? – jonrsharpe

+0

您正在取消訂閱 - takeUntil會將.subscribe保持爲活動狀態,直到您終止該訂閱爲止,或者通過從組件導航(在這種情況下,ngOnDestroy將取消訂閱作爲組件銷燬方法的一部分),或者在您想停止觀看基於流的事件點擊按鈕。它還消除了必須定義實例變量的所有樣板開銷,以便將您的.subscriptions掛起,以便您可以訪問.unsubscribe方法。 –

+0

但是你可以在'stopWatching'中加入'this.subscription.unsubscribe()'。這是更少的線條,仍然只有一個「腳手架」的財產,並可以說更多的語義。如果有的話,你的建議是*更多*樣板,除非你有一大堆你想要立即結束的訂閱。也稱你自己的東西'ng ...'可能不明智。但是謝謝你的回答。 – jonrsharpe