I have a service which pulls in data from the API
import { IStats } from './istats';
export class WebService {
BASE_URL = 'http://localhost:3000/api';
public stats = new BehaviorSubject<IStats>({
date: this.datePipe.transform(new Date(), 'dd-MM-yyyy'),
answeringMachine:0,
hangUp:0,
conversations:0
});
constructor(private http: HttpClient, private datePipe: DatePipe) {
this.getStatsbyDate('04-03-2018');
// this.getStatsbyDate(this.datePipe.transform(new Date(), 'dd-MM-yyyy'));
}
getStatsbyDate(date) {
this.http.get<IStats>(this.BASE_URL + '/stats/' + date)
.subscribe((data: IStats) => {
this.stats.next(data);
});
}
And then I have a component which subscribes to that BehavioralSubject in the service.
export class StatsComponent {
private stats: IStats;
constructor(private webService: WebService, private datePipe: DatePipe) {
this.stats = this.webService.stats.getValue();
}
I thought if the backend API doesn't have any data then the behavioralSubject returns the default values, which works as of now, but what if the backend does have data coming through then isn't it supposed to replace the default values with the values from the API? Is there anything wrong that I am doing here? Please advise!
I was able to work it out making some changes on the component code
export class StatsComponent {
private stats: IStats;
constructor(private webService: WebService, private datePipe: DatePipe) {
this.webService.stats$.subscribe(data => {
if (data !== null) { this.stats = data; }
else { this.webService.stats$.next(this.stats); }
})
}
In this way the BehavioralSubject supplies the default values from the service if there is no data from API and also vice versa.