
RxJS - 訂閱相關操作
在可觀察物件建立時,為執行可觀察物件,我們需要訂閱它。
count() 運算子
以下是一個如何訂閱可觀察物件的簡單示例。
示例 1
import { of } from 'rxjs'; import { count } from 'rxjs/operators'; let all_nums = of(1, 7, 5, 10, 10, 20); let final_val = all_nums.pipe(count()); final_val.subscribe(x => console.log("The count is "+x));
輸出
The count is 6
訂閱有一個稱為 unsubscribe() 的方法。呼叫 unsubscribe() 方法將移除用於該可觀察物件的所有資源,即該可觀察物件將被取消。以下是如何使用 unsubscribe() 方法的一個示例。
示例 2
import { of } from 'rxjs'; import { count } from 'rxjs/operators'; let all_nums = of(1, 7, 5, 10, 10, 20); let final_val = all_nums.pipe(count()); let test = final_val.subscribe(x => console.log("The count is "+x)); test.unsubscribe();
訂閱儲存在變數 test 中。我們已使用 test.unsubscribe() 取消了該可觀察物件。
輸出
The count is 6
廣告