Angular Observable to Array

时间:2018-04-10 00:57:45

标签: typescript angular5

以下不会将数组输出到控制台。范围不正确???

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Broker } from './broker';

@Injectable()
export class BrokerSurveyService {

  brokers: Broker[] = [];

  constructor(private http: HttpClient) { 
    this.getBrokers().subscribe((brokers) => { 
      this.brokers = brokers;
    });
    console.log(this.brokers); # Does NOT output to console
  }

  getBrokers() {
    return this.http.get<Broker[]>('http://www.example.com/brokers.json');
  }

}

这会将数组输出到控制台,因为它在分配后立即发送到控制台。 this范围是否不同?我很困惑为什么。

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Broker } from './broker';

@Injectable()
export class BrokerSurveyService {

  brokers: Broker[] = [];

  constructor(private http: HttpClient) { 
    this.getBrokers().subscribe((brokers) => { 
      this.brokers = brokers;
      console.log(this.brokers); # Outputs to console
    });
  }

  getBrokers() {
    return this.http.get<Broker[]>('http://www.example.com/brokers.json');
  }

}

1 个答案:

答案 0 :(得分:4)

correct

由于服务调用是异步的,因此调用subscribe时数据不会立即到达。相反,当从服务返回响应时,将调用定义为subscribe方法的参数的回调函数。

这就是为什么Subscribe中的console.log工作的原因。

如果要在代码中的某处使用数组,请使用其他方法调用

constructor(private http: HttpClient) { 
    this.getBrokers().subscribe((brokers) => { 
      this.brokers = brokers;
      useBroker(this.brokers);
    });
 }

useBroker(brokers:any){
   console.log(brokers);
}