0

Hi I have created a function which need to be loaded before a component starts loading. For that I have used AppInitializer. If I want load one function, it works. But I need both. And ngOnInit() or *ngIf also won't work as I need this function before my component loads. Here is my app.service.ts


  detail1: any;
  detail2: any;

  getDetail1() {
    return this.detail1;
  }

  getDetail2() {
    return this.detail2;
  }

  loadDetail1() {
    return new Promise((resolve, reject) => {
      this.http.get<any>(URL1)
        .subscribe(detail1 => {
          this.detail1 = detail1['respObj'];
          resolve(true);
        });
    });
  }

  loadDetail2() {
    return new Promise((resolve, reject) => {
      this.http.get<any>(URL2)
        .subscribe(detail2 => {
          this.detail2 = detail2['respObj'];
          resolve(true);
        });
    });
  }

How do I implement it in a nested function on how do I call this function before app loads. Please let know if anyone has any idea.

RKD
  • 33
  • 1
  • 8

1 Answers1

0

ngif will work since ngOnInit runs before the template loads, I would still use ngOnInit, I would instead wait until both requests emit something, store the values at scope in a single Observable and use the async pipe handle the subscription, as such:

    details$: Observable<any>;

    ngOnInit() {
       this.details = combineLatest([
            this.http.get<any>(URL1),
            this.http.get<any>(URL2)
        ]);
    }

Then in the template:

    <div *ngIf="details$ | async as details">
       // do something with -details- as the values are stored in it
    </div>

combineLatest returns an observable containing an array which has the values of your get requests, the values are stored in the same order [valuesURL1, valuesURL2].

Ultimately I would suggest moving all http requests to their own service, then inject the service within the components constructor. Currently your component is handling more responsability than it should at the moment.

Bargros
  • 521
  • 6
  • 18