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

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

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

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