2

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.

2 Answers 2

5

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

Sign up to request clarification or add additional context in comments.

2 Comments

Perfect. Thank you very much, Deborah.
So glad I've been able to help @WebDevKid, but I don't really do animation so I don't know the answer to your other question.
5

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.