subscribe
中的返回值data 和 reduce
中的 acc,product 参数的一般来源是怎样的?能系统详细描述一下吗
ngOnInit() {
this.expandedHeight = '0';
this.cartService.productAdded$.subscribe(data => {
this.products = data.products;
this.cartTotal = data.cartTotal;
this.numProducts = data.products.reduce((acc, product) => {
acc += product.quantity;
return acc;
}, 0);
}
===============================================
第一,关于subscribe(data => :
关于第一个data数据:this.cartService.productAdded$.subscribe(data =>
1.我按住Ctrl+鼠标点击poductAdded$,会跳至cart.service.ts文件,相关两行代码如下:
private productAddedSource = new Subject<any>();
productAdded$ = this.productAddedSource.asObservable();
2.这时我按住Ctrl+鼠标点击Subject<any> 或 asObservable()都会跳至 Subject.d.ts文件,相关代码如下(就是暴露一个了继承了Observable 和 ISubscription 的 Subject类):
export declare class Subject<T> extends Observable<T> implements ISubscription {
observers: Observer<T>[];
closed: boolean;
isStopped: boolean;
hasError: boolean;
thrownError: any;
constructor();
static create: Function;
lift<R>(operator: Operator<T, R>): Observable<R>;
next(value?: T): void;
error(err: any): void;
complete(): void;
unsubscribe(): void;
protected _trySubscribe(subscriber: Subscriber<T>): TeardownLogic;
protected _subscribe(subscriber: Subscriber<T>): Subscription;
asObservable(): Observable<T>;
}
,3.最终问题来了,这个 data 是如何到 subscribe 这里来的?是 subscribe 隐式地处理了很多问题吗?
(注意,关于data数据本身我是知道的,它是data.js里的假数据,import到 data.service.ts里
)
第二,关于reduce 的两个参数 acc, product:
本例中reduce有两个必需参数,第一个是匿名函数返回值acc,一个是0.我的问题就是匿名函数括号里的acc,product即(acc, product)的初始值哪里来的?并没有看到类似acc=0,product=0类似这样的操作啊?
这个data就是通过
this.cartService.productAdded$
获取到的数据,通常是JSON格式。reduce
是js中数组的一个方法,具体解释见 reduce