Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
347 views
in Technique[技术] by (71.8m points)

angular - undefined value from subscribe to observable

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

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

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...