TypeScript, Angular4 函数中数据来源问题(初级问题)

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类似这样的操作啊?

阅读 2.7k
3 个回答

这个data就是通过this.cartService.productAdded$获取到的数据,通常是JSON格式。reduce 是js中数组的一个方法,具体解释见 reduce

reduce是原来js就有的方法,acc的初始值就是reduce的第二个参数,product是遍历数组的每个值

这里面其实是观察者模式,subscibe()接受3个参数(函数),next参数就是你例子中的函数,当可观察对象发出值就会调用你写的next方法

reduce是js本身就有的,具体百度吧

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进