Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I know there is number of questions regarding this problem, but non of them helps to solve my problem. Subscribing to the service from component, it is always return undefined.. loosing my mind over this.

component:

ngOnInit() {
  this.dataService.getAllPartners().subscribe(data => 
      {this.partners = data
        console.log("data " + data);},// i can see the data returns 
      error => {
      LoggerService.error('Failed to load partners.')
    });
    console.log("Partners " + this.partners);// partners is undefined 
  }

enter image description here

service:

 private serviceUrl = '/partners';
 private headers = new HttpHeaders()
    .set('Content-Type', 'application/json');

    constructor(private httpClient: HttpClient) { }

    /**
   * Fetch  partners from the server
   */   
    getAllPartners(searchParams?: Object): Observable<Partner[]> {
      return  this.httpClient.get(Constants.BASE_SERVICE_URL + serviceUrl , {
        params: HttpRequestService.buildRequestOptions(searchParams),
        headers: this.headers
    })

}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
345 views
Welcome To Ask or Share your Answers For Others

1 Answer

So basically this line of code

console.log("Partners " + this.partners); 

is running before the code inside the .subscribe

   this.dataService.getAllPartners().subscribe(data => { 
    // What happens here is after the request has been processed
}

Thats because the subscribe is an asynchronous operation and takes some time, so you need to do your console.log inside the subscribe.

Be aware that subscriptions are long living and need to be unsubscribed with your component like this below.

import {  Subscription } from 'rxjs';

    private subscription : Subscription;
    ngOnInit() {
       this.subscription = this.dataService.getAllPartners().subscribe(data =>
            {this.partners = data;
                console.log("data " + data);}, 
            error => {
                LoggerService.error('Failed to load partners.')
            });

    }

    ngOnDestroy() {
        this.subscription.unsubscribe();
    }

But you also should not be subscribing the way you are. Ideally you should subscribe using the | async pipe inside your template as angular will then handle all of that for you.

So in your component do this

ngOnInit() {
           this.partners = this.dataService.getAllPartners();
        }

and in your template

<ng-container *ngFor="let partner of partners | async">
    // Your html markup for each partner here 
    {{partner.name}}
 </ng-container>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...