WebDevKid
WebDevKid

Reputation: 51

Angular - Updating component value, when service value changes

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.

Upvotes: 2

Views: 5441

Answers (2)

DeborahK
DeborahK

Reputation: 60518

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

Upvotes: 5

SiddAjmera
SiddAjmera

Reputation: 39432

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.

Upvotes: 5

Related Questions