我设置了一个“全局”服务,在我的 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
仅包含单个参数;即包装param1
并param2
在一些“状态类”中:
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);
}
}