I have a service file called user-status.service which calls up an api to get a value:
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { HttpService } from "../../http.service";
import { Router } from "@angular/router";
@Injectable()
export class UserStatusService {
private _userStatusResource = new BehaviorSubject<any>(null);
reload$ = this._userStatusResource.asObservable();
constructor(private router: Router, private httpService: HttpService) { }
getUserDetails() {
this.httpService.getUsersStatus()
.subscribe(
data => {
console.log(data);
this._userStatusResource.next(data.body);
},
() => console.log("")
);
}
}
Now on normal components where I want to get the value, I can't seem to get the value on oninit.
import { Component, OnDestroy, OnInit } from '@angular/core';
import { HttpService } from "../../http.service";
import { UserStatusService } from '../../shared/services/user-status.service';
import { Subscription } from "rxjs/Rx";
@Component({
selector: 'app-event-management',
templateUrl: './event-management.component.html'
})
export class EventManagementComponent implements OnInit {
userStatus: any;
private subscription1: Subscription;
constructor(private httpService: HttpService, private userStatusService: UserStatusService) {
this.subscription1 = this.userStatusService.reload$
.subscribe(
response => {
this.userStatus = response;
if ((this.userStatus.isDefaultAdmin == false))
{
alert("Do something");
}
});
}
ngOnInit() {
this.userStatusService.getUserDetails();
}
ngOnDestroy() {
this.subscription1.unsubscribe();
}
}
The value coming from the subscription is always null (the alert "Do something" will never run). How can I get the value from the service on runtime?
I should also mention the point of this service file is because I only want to call that api once in the session, there's no need for me to make repeat calls to it.