Angular-服务值更改时更新组件值 [英] Angular - Updating component value, when service value changes

查看:74
本文介绍了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).

这篇关于Angular-服务值更改时更新组件值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆