0

我设置了一个“全局”服务,在我的 Angular 应用程序中跨组件共享参数:

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';

@Injectable()
export class ParameterService {

  param1 = new BehaviorSubject(null);
  publishParam1(data: number) {
    this.param1.next(data);
  }

  param2 = new BehaviorSubject(null);
  publishParam2(data: number) {
    this.param2.next(data);
  }

}

需要这些参数中的一个或两个的组件可以订阅,并在这些更改时得到通知:

  private subscriptions: Array<Subscription> = [];
  param1: number; // keep local copies of the params
  param2: number;

  ngOnInit(): void {

    this.subscriptions.push(this._parameterService.param1.subscribe(
      data => {
          console.log("param1 changed: " + data);
          if (data != null) {
            this.param1 = data;
            // NB! this.param2 may be undefined!
            this.getDataFromAPI(this.param1, this.param2);
        }
      }
    ));

    this.subscriptions.push(this._parameterService.param2.subscribe(
      data => {
          console.log("param2 changed: " + data);
          if (data != null) {
            this.param2 = data;
            // NB! this.param1 may be undefined!
            this.getDataFromAPI(this.param1, this.param2);
        }
      }
    ));
  }

  ngOnDestroy() {
    // https://stackoverflow.com/questions/34442693/how-to-cancel-a-subscription-in-angular2
    this.subscriptions.forEach((subscription: Subscription) => {
            subscription.unsubscribe();
        });
  }

param1并由异步param2初始化AppComponent,因此订阅这两个参数的组件将以任意顺序“通知”(接收值)。getDataFromAPI每当任一参数更改时都应该获取新数据,因此两个订阅都调用该方法,但另一个参数可能仍然是undefined.

显然,这可以通过简单地在调用之前检查是否定义了其他参数来轻松解决getDataFromAPI,但我想知道处理这种(当然很常见)场景的最佳方法是什么?我应该使用 promises 还是 await 来确保getDataFromAPI仅在定义了两个(所有)参数时才调用它?

想到的一个简单想法是确保ParameterService仅包含单个参数;即包装param1param2在一些“状态类”中:

export class StateObject {
    param1: number;
    param2: number;

    constructor() { }
}

这样ParameterService就变成了,

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { StateObject } from './stateobject';

@Injectable()
export class ParameterService {

  state = new BehaviorSubject(null);
  publishState(data: StateObject) {
    this.state.next(data);
  }
}
4

1 回答 1

1

你可以试试:

let subscription  = Rx.Observable.combineLatest(
    this._parameterService.param1,
    this._parameterService.param2
  )
  .subscribe(data => {
      console.log("param1 or param2 changed: " + data);
      let [p1, p2] = data;
      this.getDataFromAPI(this.param1 = p1, this.param2 = p1);
    })
);

或带有投影功能:

let subscription  = Rx.Observable.combineLatest(
    this._parameterService.param1,
    this._parameterService.param2,
    (p1, p2) => { p1: p1, p2: p2 }
  )
  .subscribe(data => {
      console.log("param1 or param2 changed: " + data);
      this.getDataFromAPI(this.param1 = data.p1, this.param2 = data.p2);
    })
);

combineLatest API 参考

于 2017-09-06T09:14:46.027 回答