I've tried searching on google but couldn't find solution, So here is the problem:
I'm trying to load a data from server using http module in angular but the problem is that particular data is required by multiple components here is what i tried so far:
@Injectable()
export class CoreService {
data: any = null;
Event: Observable<Object>;
isLoadingData: boolean = false;
constructor(private httpService: HttpService) {
if(!isNull(this.data)) { return observer.next({data:this.data, isBusy: isLoading}) } // If Data is not null then return the data
if(this.isLoadingBaseDirectory) {
return observer.next({data:this.isLoadingBaseDirectory, isBusy: this.isLoading}) // if http call is busy loading the data then return isBusy true
}
this.isLoading = true; // Data is empty and we are not loading data, then set isLoading flag to true
this.httpService.get(`coreEnv/getPodiumBaseDirectory`).map((res:Response) => { return res.json() }).subscribe((data) => {
this.data = data; // data load complete
this.isLoading = false;
observer.next({data:this.data, isBusy: this.isLoading});
})
}
}
// Component ngOnInit Method:
this.isBusy = true; // Component Loading Flag
this.coreService.baseDirectoryEvent.subscribe((data) => {
if(!data['isBusy']) {
this.data = data['data'];
this.isBusy = false;
}
})
Now if i use above code in the multiple component and load them both in the same page, the second component does get the response isBusy flag true from the service because first component tried to load the data which sets isBusy flag to true in the service, but when service successfully loaded the data from server it does not trigger last observer.next for second component but first component get the data.