【发布时间】: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