定义user.id之后可观察到的创建发射

Indraraj26

定义后,我无法发出用户ID。这就是我所知道的,一旦您订阅了observable,它就会监听变化并发出声音。定义用户ID时,是否可以发出任何运算符。

我也尝试了of和新的Observable运算符,得到的输出是相同的。

  constructor() {
    setTimeout(() => {
      this.user.id = 1
      ,5000})
   }


   getUserIdChat(): Observable<any> {
      return Observable.create(data=> {
        console.log(" i called")
        if(typeof this.user.id != 'undefined') {
          console.log('next called')
          data.next(this.user.id);
          data.complete();
        }
      })
    }

constructor(private user: UserService) {
    this.user.getUserIdChat().subscribe(data => {
      console.log('data from user', data)
    })
   }

我应该在控制台中得到输出1

Nosheep

做一个主题。

userSubject = new Subject<number>();

 constructor() {
    setTimeout(() => {
      this.user.id = 1;
      this.userSubject.next(this.user.id)
      ,5000})
   }

   getUserIdChat(): Observable<any> {
      return userSubject.asObservable()
    }


constructor(private user: UserService) {
    this.user.getUserIdChat().subscribe(data => {
      console.log('data from user', data)
    })
   }

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章