Angular - 当服务值改变时更新组件值

问题描述:

我有多个组件(在 NgFor 循环中)调用相同的服务.

I have multiple components (in an NgFor loop) that call the same service.

我想要的是,当一个组件更改同一服务中的值时,该新值会被发送到调用该服务的每个组件,并随后更新组件变量中的该值.

What I would like is that when one component changes a value in that same service, that new value then gets sent to every component that calls that service and subsequently updates that value in a component variable.

我希望这是有道理的.

如果您需要更多信息,请告诉我.

If you need some more information, please let me know.

您可以使用简单的 getter 代替 BehaviorSubject(在简单场景中通常是矫枉过正的):

Instead of a BehaviorSubject (which are often overkill in simple scenarios), you can use simple getters:

服务有一些数据要共享:

Service has some data to share:

export class ProductParameterService {
  showImage: boolean;
  filterBy: string;

  constructor() { }

}

组件只使用一个 getter,当服务值改变时,任何绑定到属性的模板变量都会自动更新:

Components just use a getter and any template variable bound to the property is automatically updated when the service value changes:

get showImage(): boolean {
    return this.productParameterService.showImage;
}

在模板中:

                        <img *ngIf='showImage'
                             [src]='product.imageUrl'
                             [title]='product.productName'>

如果应用程序中任何位置的任何组件使用该服务更改 showImage 的值,视图将自动更新(利用 Angular 的内置更改检测).

If any component anywhere in the application uses the service to change the value of showImage, the view will automatically update (leveraging Angular's built in change detection).