我正在尝试使用角度服务通过可观察的方式存储和传递数据。
这是我的服务
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)!
我尝试通过设置公共类型并使用getValue()来直接访问该值。 我尝试复制对象以使其不传递引用,但未进行任何更改。
这是我的下标组件ngOnInit:
ngOnInit(): void {
this.legalToUpdate = this.legalService.currentLegal$.subscribe((legal) => {
console.log(legal)
})
}
这是怎么了? 谢谢
答案 0 :(得分:1)
您有这种行为,因为您在不同的模块中使用了它,并且创建了不同的实例。
将您的服务设置为root:
@Injectable({ providedIn: 'root' })
export class LegalService implements HttpInterceptor { }