首页 > 解决方案 > 当我的全局共享服务中的任何内容更新时,为什么我的组件对象不会自行更新?角

问题描述

我有这项服务:

    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一个组件中的变量时,尽管它被引用,但它不会在其他组件中更新回来,因此我希望立即进行更改。

我究竟做错了什么?

标签: javascriptangularreferenceangular-servicesangular-components

解决方案


它不会更新,因为新值没有“发送”到已经启动的角度组件。

相反,您应该使用 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);

推荐阅读