Angular 如何等待直到创建所有可观察的观察者

Angular 如何等待直到创建所有可观察的观察者,angular,typescript,rxjs,Angular,Typescript,Rxjs,我正在尝试用Observable构建消息传递系统。我的代码是这样的,非常简单。 但我有幻灯片问题,有时在创建storageObserver之前调用newMessage方法,我会遇到这个错误 无法读取null的属性“next” 显然,我可以像这样签入新消息 newMessage(message: any) { if(this.storageObserver == null) { setTimeout(() => { this.storageObserve

我正在尝试用Observable构建消息传递系统。我的代码是这样的,非常简单。 但我有幻灯片问题,有时在创建storageObserver之前调用newMessage方法,我会遇到这个错误

无法读取null的属性“next”

显然,我可以像这样签入新消息

newMessage(message: any) {
    if(this.storageObserver == null) {
      setTimeout(() => {
         this.storageObserver.next(message);
      }, 500)
    } else {
      this.storageObserver.next(message);
    }
}

但我真的不喜欢这种类型的黑客。是否有合适的方法等待观察者被创建?

我怀疑您希望能够手动“馈送”观察者,只要您愿意,但还有另一种方法可以做到这一点

我喜欢这样写:

private storageSubject: Subject<any>;

constructor(private auth: AuthenticationService, private http: HttpClient) {
    this.storageSubject = new Subject<any>();
    this.storage$ = this.storageSubject.asObservable(); 
}

// This is a public observable that can be subscribed to.
// Do not forget to unsubscribe.
storage$: Observable<any>;

newMessage(message: any) {
    this.storageSubject.next(message);
}
private-storageSubject:Subject


注意:如果希望观察对象具有初始值,可以使用
BehaviorSubject
。它总是在subscribtion之后立即给出最后一个值,如果您希望该值具有某种形式的状态,这会更有用。

在这种情况下,您可以使用Subject,而不是Observable。无论如何,您可以在构造函数之外定义Observable
private storageSubject: Subject<any>;

constructor(private auth: AuthenticationService, private http: HttpClient) {
    this.storageSubject = new Subject<any>();
    this.storage$ = this.storageSubject.asObservable(); 
}

// This is a public observable that can be subscribed to.
// Do not forget to unsubscribe.
storage$: Observable<any>;

newMessage(message: any) {
    this.storageSubject.next(message);
}