源代碼:
import { of } from 'rxjs';
import { Injectable } from '@angular/core';
import { map } from 'rxjs/operators';
import { tap } from 'rxjs/operators';
@Injectable()
export class JerrySandBoxService{
name = 'Jerry';
print(){
const observable = of(1, 2, 3);
const newObservable = observable.pipe(
tap(num => console.log(num)),
map(num => 'hello world: ' + num)
);
newObservable.subscribe(data => console.log(data));
}
}
執行pipe之前先執行map函數:
map返回一個新的函數:
然後執行pipe函數:...operations變長參數,包含tap和map兩個操作。
pipeFromArray的實現藉助了JavaScript的closure閉包:
到目前爲止,我們傳入的tap和map裏的箭頭函數都未執行,直到subscribe方法的調用:
此時對於數組裏的1,2,3,先執行管道里的tap和map操作,再把map操作的輸出,作爲輸入去執行subscribe裏指定的回調: