|
我們可以在 app.module.ts 里使用如下代碼,獲得當(dāng)前 cart id: export class AppModule {
constructor(_cart: ActiveCartService){
_cart.getActiveCartId().subscribe((data) =>
console.log('Jerry: ', data));
console.log(_cart);
}
}打印輸出:
在執(zhí)行 Angular 依賴注入框架時,首先依次執(zhí)行 pipe 操作符里的 Operator 邏輯,比如 take(1) :
take 只是簡單的返回一個 function,該 function 的觸發(fā)時機?
在 pipe 操作里被調(diào)用:
此時再次返回一個新的函數(shù):
Observable 的 lift 操作:
關(guān)于 take(1) 的使用場合: 當(dāng)開發(fā)人員只對 stream 的第一個發(fā)射值感興趣時,可以使用 take。 比如我們想查看用戶在進(jìn)入頁面時首先點擊了什么,或者想訂閱 click 事件并獲取第一次點擊。 另一個用例是當(dāng)需要在特定時間點進(jìn)行數(shù)據(jù)快照的采集,但不需要進(jìn)一步排放時。 例如,用戶令牌更新流,或基于 Angular 應(yīng)用程序中的流的路由保護(hù)。 如果想根據(jù)某些邏輯或另一個 observable 獲取可變數(shù)量的值,可以使用 takeUntil 或 takeWhile. take 與 skip 相反,其中 take 將采用前 n 個發(fā)射,而 skip 將跳過前 n 個發(fā)射。 下列例子會輸出 1: // RxJS v6+
import { of } from 'rxjs';
import { take } from 'rxjs/operators';
//emit 1,2,3,4,5
const source = of(1, 2, 3, 4, 5);
//take the first emitted value then complete
const example = source.pipe(take(1));
//output: 1
const subscribe = example.subscribe(val => console.log(val));下列代碼會輸出整數(shù)序列 0,1,2,3,4: // RxJS v6+
import { interval } from 'rxjs';
import { take } from 'rxjs/operators';
//emit value every 1s
const interval$ = interval(1000);
//take the first 5 emitted values
const example = interval$.pipe(take(5));
//output: 0,1,2,3,4
const subscribe = example.subscribe(val => console.log(val));下列代碼會將第一次點擊 div 標(biāo)簽的鼠標(biāo)坐標(biāo),顯示在 HTML 頁面上: // RxJS v6+
import { fromEvent } from 'rxjs';
import { take, tap } from 'rxjs/operators';
const oneClickEvent = fromEvent(document, 'click').pipe(
take(1),
tap(v => {
document.getElementById(
'locationDisplay'
).innerHTML = `Your first click was on location ${v.screenX}:${v.screenY}`;
})
);
const subscribe = oneClickEvent.subscribe();div 元素: <div id="locationDisplay"> Where would you click first? </div> pipe 函數(shù)里傳入的所有操作,都記錄在變量 fns 里了:
最后 activeCartId$ 存放的就是 pipe 調(diào)用的返回結(jié)果:
開始執(zhí)行 subscribe 了:
還得把 withLatestFrom , map 和 distinctUntilChanged 都依次執(zhí)行一遍:
從調(diào)試上下文能夠明顯看出,先執(zhí)行的 filter 里的匿名函數(shù),再執(zhí)行的 map 里的匿名函數(shù):
|
|
|