【问题标题】:rxjs pubsub : convert Observable<any> to string / objectrxjs pubsub : 将 Observable<any> 转换为字符串/对象
【发布时间】:2017-07-10 18:49:57
【问题描述】:

我有以下 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});

在监听组件中,我正在尝试订阅此服务,但我不确定如何将 Observable 转换为 String(在这种情况下)或任何自定义对象

this._pubSubService.subscribe("loggedInUser"). ?? //not sure how to get the data here.

我是 rxjs 概念的新手,因此尝试使用我的项目代码库中的现有代码 sn-ps,看看它是否有意义。您能否指导我了解使用 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'.

【问题讨论】:

  • 你不能序列化 observable
  • @RomanC 你能指导我一个可以帮助我的场景的例子,然后我可以尝试相同的线路。谢谢。

标签: angular rxjs


【解决方案1】:

问题在于您混合了同步和异步代码。当您登录 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 记录它,那么您将获得数据。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-25
    • 2021-05-24
    • 2023-03-23
    • 2016-12-25
    • 2018-02-19
    • 2021-04-11
    相关资源
    最近更新 更多