我的观察能力有问题。我试图使用async
管道显示评论:
<p *ngFor="let comment of client_comments$ | async">
{{ comment }}
</p>
我按如下方式初始化comments$
:
// Ionic lifecycle hook for view loading
ionViewWillEnter() {
this.client_comments$ = this.commentService.getClientComments()
}
并且服务看起来像:
@Injectable()
export class CommentsProvider implements OnInit {
private client_comments = new BehaviorSubject([]);
client_comments$: Observable<any[]>
constructor(private clientService: ClientService) {
this.client$ = this.clientService.clientStream$
this.client$.subscribe( client => {
this.client = client
})
}
initializeClientComments() {
let client_comments = _.orderBy(this.client.comments, 'created_at', 'desc')
this.client_comments$ = this.client_comments.asObservable()
this.client_comments.next(client_comments)
}
addComment(comment) {
let clientCommentArray = _.cloneDeep(this.client_comments.getValue())
clientCommentArray.unshift(comment)
this.client_comments.next(clientCommentArray)
}
getClientComments() : Observable<any[]> {
this.initializeClientComments()
return this.client_comments$
}
}
当我添加评论时,该值不会保留,我相信由于调用initializeClientComments()
因为我将getClientComments()
更改为:
getClientComments() : Observable<any[]> {
if (_.isEmpty(this.client_comments.getValue())) {this.initializeClientComments()}
return this.client_comments$
}
注释数组按预期更新。但是当我使用更新的getClientComments()
,并从一个客户端更改为另一个客户端时,该视图将显示第一个客户端的注释,并且不会随客户端更改。我认为构造函数没有触发,导致客户端没有更新。
客户服务:
@Injectable()
export class ClientService implements OnInit {
private client = new BehaviorSubject("");
clientStream$ = this.client.asObservable();
constructor (private http: Http, private toastCtrl: ToastController, public storage: Storage, private app: App, private emailComposer: EmailComposer, private platform: Platform, private globalVarService: GlobalVariablesProvider) {}
setClient(new_client) {
this.client.next(new_client)
}
}
我应该如何重构这个以允许评论流保持同步?