在 Angular 中,您可以使用UIService通过BehaviorSubject实现共享状态信息。如果您有两个组件需要这些信息,您可能认为需要在每个组件中订阅一次BehaviorSubject。这将导致重复订阅并可能导致意外的行为。
为了避免重复订阅,可以在UIService中创建一个公共Observable,然后在每个组件中订阅该Observable。这将确保每个组件只订阅一次,并且避免重复订阅。以下是相应的示例代码:
UIService:
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
@Injectable()
export class UIService {
private readonly _loading = new BehaviorSubject(false);
readonly loading$ = this._loading.asObservable();
set loading(value: boolean) {
this._loading.next(value);
}
}
Component 1:
import { Component, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs/Subscription';
import { UIService } from '../ui.service';
@Component({...})
export class MyComponent1 implements OnDestroy {
private subscription = new Subscription();
loading: boolean;
constructor(private uiService: UIService) {
this.subscription.add(
uiService.loading$.subscribe(value => (this.loading = value))
);
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
Component 2:
import { Component, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs/Subscription';
import { UIService } from '../ui.service';
@Component({...})
export class MyComponent2 implements OnDestroy {
private subscription = new Subscription();
loading: boolean;
constructor(private uiService: UIService) {
this.subscription.add(
uiService.loading$.subscribe(value => (this.loading = value))
);
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
现在,在UI服务中创建了名为“ loading$ ”的共享Observable,每个组件只需