javascript - 当我的全局共享服务中的任何内容更新时,为什么我的组件对象不会自行更新?角
问题描述
我有这项服务:
export class RecipeService{
selectedRecipe: Recipe = 'xyz';
}
我有这个组件使用这个服务:
export class RecipesComponent implements OnInit {
selectedRecipe: Recipe;
constructor(private recipeService: RecipeService) { }
ngOnInit(): void {
this.selectedRecipe = this.recipeService.selectedRecipe;
}
}
该服务是在app.module.ts
注入中定义的,这意味着所有组件都获得相同的实例。
我的问题是,每当我更新我的selectedRecipe
一个组件中的变量时,尽管它被引用,但它不会在其他组件中更新回来,因此我希望立即进行更改。
我究竟做错了什么?
解决方案
它不会更新,因为新值没有“发送”到已经启动的角度组件。
相反,您应该使用 observables。
例如:
/* service */
private recipe = "xyz";
public recipeSubject: BehaviorSubject<string> = new BehaviorSubject(this.recipe);
// when changing the recipe
recipeSubject.next(this.recipe);
/* component */
this.service.recipeSubject.subscribe(res => this.recipe = res);
推荐阅读
- mongodb - 在 mongodb 中查找嵌套数组对象中存在的重复字段名称记录
- r - 对于每一行,返回特定数字的多列索引
- c# - 嵌套的 if 语句在没有 else 语句的情况下正确运行,但是当添加 else 语句时,它会跳过我的 if
- c# - SQLite 是否支持表值参数?
- python - 在makefile中运行python脚本不起作用
- javascript - Express JS TypeError: Cannot read properties of undefined (reading '0') SQL query error
- ssl - 双向 TLS 身份验证中的飞行 CA 证书
- javascript - 浏览器的虚拟/屏幕键盘
- java - 网页内容内的文件夹中的 JSP 无法访问 servlet
- sql - 未找到 SQLServer UDF