1

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.

Touqeer Shafi
  • 5,084
  • 3
  • 28
  • 45

2 Answers2

1

Are you using routing? If so, you could define a component-less parent route with a resolver. The resolver can get the data and all of the children can then access that data.

I have an example here: https://github.com/DeborahK/Angular-Routing in the APM-Final folder. Check out the product-resolver.service.ts.

Any route that is a child of this parent route can then access the data using syntax similar to this:

ngOnInit(): void {
    this.route.parent.data.subscribe(data => {
        this.product = data['product'];
    });
}

This is using subscribe on the data property because in my example the data could be re-retrieved with different parameters.

DeborahK
  • 57,520
  • 12
  • 104
  • 129
1

As @Günter Zöchbauer mentioned in his comment that to achieve this functionality see answer: What is the correct way to share the result of an Angular 2 Http network call in RxJs 5?

Worked for me!

Community
  • 1
  • 1
Touqeer Shafi
  • 5,084
  • 3
  • 28
  • 45