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() { }
}
组件仅使用吸气剂,并且当服务值更改时,绑定到属性的任何模板变量都会自动更新:
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).