我正在尝试使用 Angular 服务通过可观察来存储和通信数据。
这是我的服务
public _currentLegal = new BehaviorSubject({
name: 'init',
_id: 'init',
country: 'init',
city: 'init',
});
readonly currentLegal$ = this._currentLegal.asObservable();
constructor(private http: HttpClient) {
}
setCurrentLegal(legal) {
const legaltest = {
name: 'test',
_id: 'test',
country: 'test',
city: 'test',
}
console.log('emitting next value from', legal.name)
this._currentLegal.next({ ...legaltest });
}
我有一个调用 setCurrentLegal 的组件,console.log 被触发并且正确。然后,我导航到另一个订阅 currentLegal$ observable 的组件,并且该值仍然相同(init)!
我尝试通过设置公共(public)类型并使用 getValue() 直接访问该值,同样。 我尝试复制该对象以不传递引用,但没有更改任何内容。
这是我的订阅组件 ngOnInit :
ngOnInit(): void {
this.legalToUpdate = this.legalService.currentLegal$.subscribe((legal) => {
console.log(legal)
})
}
这里出了什么问题? 谢谢
最佳答案
您出现此行为是因为您在不同的模块中使用它并且它创建了不同的实例。
将要提供的服务放在根目录中:
@Injectable({ providedIn: 'root' })
export class LegalService implements HttpInterceptor { }
关于javascript - BehaviourSubject 问题,next() 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61646728/