Ajay
Ajay

Reputation: 4251

Not able to fetch an array of results from angular2 service

This is my service code to fetch an array of results:

  getIndustries(): Observable<any> {
    return this.http.get(`${IndustriesService.BASE_URI}/?searchTerm=`)
                    .map((res: Response) => res.json())
                    .catch((err: any) => Observable.throw('Server Error'));
  }

Below is my components constructor and the method to communicate with the above defined service.

  protected searchData: Array<Industry>;
  constructor( private completerService: CompleterService,
               private route: ActivatedRoute,
               private industriesService: IndustriesService) { 
      this.fetchIndustryCodes();
    }

  private fetchIndustryCodes(): Subscription {
    return this.route.params
      .switchMap((industries: Industry[]) => this.industriesService.getIndustries())
      .subscribe((industries_data: Industry[]) => {
        this.searchData = industries_data
      });
  }

when I am trying to print this searchData in the constructor it prints a Subscription object. I am not sure how to fetch the data through above mentioned subscription.

Any direction on this would be a great help!

Upvotes: 0

Views: 47

Answers (1)

Ashish Ranjan
Ashish Ranjan

Reputation: 12950

As far I have understood, you want to use searchData in your constructor, but you are unable coz the async call takes time and the code in the constructor executes before fetchIndustryCodes() completes. If this is the case, then why don't you subscribe and wait in the constructor itself?

constructor( private completerService: CompleterService,
           private route: ActivatedRoute,
           private industriesService: IndustriesService) { 

            this.fetchIndustryCodes().subscribe(
            (industries_data) => {
                this.searchData = industries_data;
                // whatever you want to do here.
            }, (err) => {console.log("error here")});
}


 private fetchIndustryCodes(): Observable<type> {
    return this._activatedRoute.params
        .switchMap((industries) => this.industriesService.getIndustries())
        .catch((err) => {console.log(err); return "service error";})
}

Upvotes: 1

Related Questions