从订阅到可观察的不确定值

时间:2019-01-03 17:14:55

标签: angular

我知道有关此问题的问题很多,但没有一个可以帮助解决我的问题。 订阅来自组件的服务,它总是返回undefined ..使我对此感到迷茫。

组件

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

服务

 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
    })

}

1 个答案:

答案 0 :(得分:0)

所以基本上这行代码

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

.subscribe

中的代码之前运行
   this.dataService.getAllPartners().subscribe(data => { 
    // What happens here is after the request has been processed
}

那是因为订阅是异步操作并且需要一些时间,所以您需要在订阅内部进行console.log。

请注意,订阅的寿命很长,需要像下面这样取消订阅您的组件。

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();
    }

但是您也不应遵循自己的方式。理想情况下,您应该使用模板内的| async管道进行订阅,因为angular会为您处理所有这些事情。

因此在您的组件中执行

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

并在您的模板中

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