我有以下pubsub服务:
export class PubSubService {
subjects: Map<string, Subject<any>> = null;
constructor() {
this.subjects = new Map<string, Subject<any>>();
}
publish(data: { key: string, value: any }): void {
let subject = this.subjects.get(data.key);
if (!subject) {
subject = new Subject<any>();
this.subjects.set(data.key, subject);
}
subject.next(data.value);
}
subscribe(key: string): Observable<any> {
let subject = this.subjects.get(key);
if (!subject) {
subject = new Subject<any>();
this.subjects.set(key, subject);
}
return subject.asObservable();
}
}
我是这样从AppComponent发布的 -
this.loggedInUser = 'John';
this. _pubSubService.publish({key:"loggedInUser", value:this.loggedInUser});
在倾听组件中,我尝试订阅此服务,但我不确定如何将可观察转换为 字符串(在这个案例)或任何 自定义对象 。
this._pubSubService.subscribe("loggedInUser"). ?? //not sure how to get the data here.
我是rxjs概念的新手,因此尝试使用我的项目代码库中的现有代码片段,看看它是否有意义。您能否指导我使用pubsub模型发布和订阅主题的正确方法。
P.S - 早些时候我使用了不同的方法并且工作正常 - Angular 4 - rxjs BehaviorSubject usage in Service但后来我被要求遵循更通用的pubsub模型,因此尝试相同。
更新1 -
我刚刚在我的问题中发现了拼写错误,对不起。我这样订阅了 -
this._pubSubService.subscribe("loggedInUser").subscribe(...). //What should I be doing here, should I use Map?
我试过跟随 -
this.subscription = this._pubSubService.subscribe("loggedInUser").subscribe(data=>{this.loggedInUser=data});
console.log('this.user::'+this.loggedInUser);//Prints 'undefined'.
答案 0 :(得分:0)
问题是您混合了同步和异步代码。当您记录loggedInUser
时尚未设置它:
this.subscription = this._pubSubService.subscribe("loggedInUser").subscribe(data=>{
//this code runs asynchronous
this.loggedInUser=data
});
//the following code runs directly after the subscribe synchronous
console.log('this.user::'+this.loggedInUser);//Prints 'undefined'.
如果您要设置loggedInUser
并从subscribe
进行记录,那么您将获得数据。