gpt4 book ai didi

Angular 2+ 仅在变化时订阅 observable

转载 作者:行者123 更新时间:2023-12-02 14:21:14 24 4
gpt4 key购买 nike

所以这是场景。我有一个带有BehaviorSubject 的用户服务和一个返回此BehaviorSubject 的可观察值的方法。我的第二个文件是订阅可观察对象的 header 组件。问题是..是否可以仅订阅更改,或者我是否需要在 this.userSubject.next(this.user) 之前添加一些逻辑?

这里是代码供引用:

// user.service.ts
user: User;
private userSubject = new BehaviorSubject<User>(new User({}));

keepUpdated = () => {
this.tokenService.tokenStream()
.subscribe(token => {
this.user.update(token);
this.userSubject.next(this.user);
});
}

这里

// header.component.ts
ngOnInit() {
this.userService.keepUpdated();
this.userService.userStream()
.subscribe(user => {
// Here is the problem. This console.log gets called everytime userSubject.next(this.user) send something. I would like it only only to be called if the user is different from the previous one.
console.log(user);
});
}

最佳答案

您可以使用 distinctUntilChanged 运算符 ( documentation ):

ngOnInit() {
this.userService.keepUpdated();
this.userService.userStream()
.distinctUntilChanged()
.subscribe(user => {
console.log(user);
});
}

这应该通过与前一个值进行比较来过滤每个发出的值,如果不同,则将调用订阅,否则不会。

关于Angular 2+ 仅在变化时订阅 observable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44043635/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com