从Angular 2中的Service中获取Json文件

NoI*_*his 3 http observable typescript angular

我有服务.在构造函数中:

export class Service {

  _data: any

  constructor(private http: Http) {
    this.http
      .get('../assets/my_json_file.json')
      .map(x => x.json() )
      .subscribe( (data) => 
        this._data = data
      )
    console.log(this._data)
  }
Run Code Online (Sandbox Code Playgroud)

console.log收益undefined虽然它显示的数据,如果console.log被移动到传递给函数subscribe.

我的目标是getStuff()在服务中拥有许多功能,可以通过应用程序调用ngOnInit下拉菜单和内容的值

看到这一点,但没有帮助弄清楚出了什么问题

Gün*_*uer 6

this.http.get('../assets/my_json_file.json')是异步的,这意味着调度服务器被安排在以后执行,当服务器的响应到达时,最终传递的回调.subscribe(...)将被响应调用."已调度"表示将在事件队列中添加任务,以便在完成先前计划的任务时执行.

http.get(...)预定的呼叫console.log(this._data)将被执行.这是在甚至启动对服务器的调用之前.

http.get(...)电话时,返回的观察到的也只是安排http.get(...)预订了,因为观测是懒惰.

使用map(...)而不是subscribe(...)返回Observable而不是Subscription允许服务的用户将其自己的代码链接到响应事件.

@Injectable()
export class Service {

  _data: any

  constructor(private http: Http) {}

  getData() {
    this.http
      .get('../assets/my_json_file.json')
      .map(x => x.json() )
      .map( (data) => 
        this._data = data
      )
    console.log(this._data)
  }
}
Run Code Online (Sandbox Code Playgroud)

在组件中,您可以使用它

export class MyComponent {
  constructor(service:Service) {
    // `subscribe` actually initiates the call to the server
    service.getData().subscribe(result => console.log(result));
  }
}
Run Code Online (Sandbox Code Playgroud)

另请参阅在RxJs 5中共享Angular 2 Http网络调用结果的正确方法是什么?

这样,您可以在实例化服务时启动对服务器的调用,而不仅仅是在使用该服务的组件订阅之后.