Angular - Updating component value, when service value changes

北城以北 提交于 2020-01-17 01:25:06

问题


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.

I hope that makes sense.

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


回答1:


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;
}

In template:

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

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).




回答2:


Just create a SharedService like this:

import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';

@Injectable()
export class SharedService {

  private sharedData: BehaviorSubject<any> = new BehaviorSubject<any>(null);
  sharedData$: Observable<any> = this.sharedData.asObservable();

  setSharedData(sharedData) {
    this.sharedData.next(sharedData);
  }

}

This service can then be injected in the components where you want to share the data.

To set the data, call the setSharedData. To get the latest changes on the sharedData, subscribe to the sharedData$ Observable right in the ngOnInit of the component.



来源:https://stackoverflow.com/questions/53730983/angular-updating-component-value-when-service-value-changes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!