Tanzeel
Tanzeel

Reputation: 5018

How to change value of a variable in service and reflect it in a component that uses that service

I need a small help. I've a component and a service. The component is relying upon a variable whose value depends upon another variable which is in a service. The variable (one which is in service) is initially false but it should become true after getting the response (I'm using some Observable-Subscribe code at this point to mimic an HTTP GET call). Now the same true value is not reflecting back in my component. That's the problem. Here is the code:

app.component.html

<h2>Current status: {{ status }}</h2>
<button (click)="onButtonPress()" >Click</button>

app.component.ts

export class AppComponent {
  status: boolean;
  constructor(private _myService: MyserviceService) {}
  ngOnInit() {
    this.status = this._myService.serviceStatus;
  }
  onButtonPress() {
    this._myService.takeAction();
  }
}

myservice.service.ts

export class MyserviceService {
  serviceStatus: boolean = false;
  constructor() {
  }
  takeAction() {
    interval(1000)
    .pipe(take(5), toArray())
    .subscribe((res) => {
      console.log(res);
      this.serviceStatus = true;
    });
  }
}

I've created one stackblitz. Please have a look and feel free to point out mistakes in the code. Thanks.

Upvotes: 1

Views: 1801

Answers (1)

Mateusz Ścigała
Mateusz Ścigała

Reputation: 196

Please try to create BehaviorSubject variable in service, e.g. serviceStatus = new BehaviourSubject(false); // default value is false and in the takeAction method change value of serviceStatus variable to true, e.g. this.serviceStatus.next(true);

In your app.component.ts in ngOnInit subscribe to serviceStatus variable, e.g. this._myService.serviceStatus.pipe(takeUntil(this.destroy$)).subscribe(data => this.status = data); // takeUntil is for unsubscribing when component is destroyed - protect from memory leak

Upvotes: 2

Related Questions