【问题标题】:Observables involving other observable涉及其他 observable 的 Observable
【发布时间】:2017-11-17 09:10:52
【问题描述】:

我有一个问题,我的一个 observable 依赖于另一个 observable,但是当父 observable 更新时,孩子似乎没有更新。

ClientService(父级)

@Injectable()
export class ClientService {

  private client =  new BehaviorSubject("");
  clientStream$ = this.client.asObservable();

  }
}

评论服务(子)

@Injectable()
export class CommentsProvider {
  private client$: Observable<any>;
  private comments = new BehaviorSubject([]);
  comments$: Observable<any[]>

  constructor(private clientService: ClientService) {
    this.initializeComments()
  }

  initializeComments() {
    this.client$ = this.clientService.clientStream$
    this.comments$ = this.comments.asObservable()

    this.client$.subscribe( client => {
      for ( let comment of client.comments ) {
        this.addComment(comment)
      }
    })
  }

  addComment(comment) {
    let commentArray = _.cloneDeep(this.comments.getValue());
    commentArray.push(comment)
    this.comments.next(commentArray)
  }

  getComments() : Observable<any[]> {
    return this.comments$
  }
}

在我看来,我称之为组件:

`this.comments$ = this.commentService.getComments();` 

并使用以下命令显示结果:

*ngIf="this.comments$ | async as comments ..."

如果我调用addComment(),则数组会更新,但是,当我向client.comments 添加评论时,数组不会更新。有没有办法将更改通知订阅者client.comments

【问题讨论】:

  • 你们的服务是怎样提供的?它们都是单例服务(应用范围)吗?
  • 是的,他们是。他们应该是别的东西吗?
  • na,单身应该不错。你能把你的代码添加到when I add a comment to client.comments, the array is not updated的ClientService@

标签: angular rxjs observable


【解决方案1】:

我可能遗漏了一些东西,但是 ClientService 中没有任何东西可以添加到 BehaviorSubject 中。

@Injectable()
export class ClientService {

  private client =  new BehaviorSubject("");
  clientStream$ = this.client.asObservable();

  }
}

变量client 是私有的,所以不能在课堂外访问。
clientStream$asObservable(),所以你不能.next(newVale) 给它新的值(至少我认为这是asObservable 的点)。
您是否只粘贴了 ClientService 的一部分? - 有两个闭卷曲,但只有一个开卷曲。

也许将此方法添加到ClientService,

addClient(newClient) {
  client.next(newClient);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-18
    • 1970-01-01
    • 1970-01-01
    • 2021-09-05
    • 1970-01-01
    • 2021-12-03
    • 2018-06-29
    相关资源
    最近更新 更多