在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/HTML5/ TypeScript, Angular4 函數(shù)中數(shù)據(jù)來源問題(初級(jí)問題)

TypeScript, Angular4 函數(shù)中數(shù)據(jù)來源問題(初級(jí)問題)

subscribe中的返回值data 和 reduce 中的 acc,product 參數(shù)的一般來源是怎樣的?能系統(tǒng)詳細(xì)描述一下嗎

  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);
      }

===============================================
第一,關(guān)于subscribe(data => :
關(guān)于第一個(gè)data數(shù)據(jù):this.cartService.productAdded$.subscribe(data =>

1.我按住Ctrl+鼠標(biāo)點(diǎn)擊poductAdded$,會(huì)跳至cart.service.ts文件,相關(guān)兩行代碼如下:

  private productAddedSource = new Subject<any>();
  productAdded$ = this.productAddedSource.asObservable();

2.這時(shí)我按住Ctrl+鼠標(biāo)點(diǎn)擊Subject<any> 或 asObservable()都會(huì)跳至 Subject.d.ts文件,相關(guān)代碼如下(就是暴露一個(gè)了繼承了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.最終問題來了,這個(gè) data 是如何到 subscribe 這里來的?是 subscribe 隱式地處理了很多問題嗎?
注意,關(guān)于data數(shù)據(jù)本身我是知道的,它是data.js里的假數(shù)據(jù),import到 data.service.ts里


第二,關(guān)于reduce 的兩個(gè)參數(shù) acc, product:

本例中reduce有兩個(gè)必需參數(shù),第一個(gè)是匿名函數(shù)返回值acc,一個(gè)是0.我的問題就是匿名函數(shù)括號(hào)里的acc,product即(acc, product)的初始值哪里來的?并沒有看到類似acc=0,product=0類似這樣的操作啊?

回答
編輯回答
蟲児飛

reduce是原來js就有的方法,acc的初始值就是reduce的第二個(gè)參數(shù),product是遍歷數(shù)組的每個(gè)值

2017年6月8日 00:00
編輯回答
情已空

這個(gè)data就是通過this.cartService.productAdded$獲取到的數(shù)據(jù),通常是JSON格式。reduce 是js中數(shù)組的一個(gè)方法,具體解釋見 reduce

2017年1月19日 16:45
編輯回答
雨萌萌

這里面其實(shí)是觀察者模式,subscibe()接受3個(gè)參數(shù)(函數(shù)),next參數(shù)就是你例子中的函數(shù),當(dāng)可觀察對(duì)象發(fā)出值就會(huì)調(diào)用你寫的next方法

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

2017年5月2日 12:22