javascript - BehaviorSubject 问题,next() 不起作用
问题描述
我正在尝试使用角度服务来存储和通过 observable 传递数据。
这是我的服务
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)
})
}
这里有什么问题?谢谢
解决方案
您有这种行为是因为您在不同的模块中使用它并且它被创建了不同的实例。
将您的服务放在根目录中:
@Injectable({ providedIn: 'root' })
export class LegalService implements HttpInterceptor { }
推荐阅读
- python - 如何使用字典扫描列表的部分外观?
- html - Node JS 使用 css 提供 html 文件
- javascript - 从前端上传图像并将其显示在用户的个人资料页面上
- r - 如何在 R Shiny Web 应用程序中减小侧边栏面板的宽度?
- dask - 如何将多个参数传递给 dask.distributed.Client().map?
- javascript - 无法在 Chrome 扩展 API 中将脚本执行到新选项卡中
- javascript - 过滤和显示嵌套对象数据
- c# - 在 Unity ARCore for Android 中动态创建 4 个已知点之间的平面
- python - algolia-django 在 algolia 索引中更新多对多模型的问题
- javascript - 如何在`while(true)`循环中每隔`n`和`m`秒调用两个异步函数?