在 Angular 2 中使用来自服务的 Json 文件

Consume Json file from Service in Angular 2

我有一个服务。 在构造函数中:

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

console.log returns undefined 尽管如果将 console.log 移动到传递给 subscribe 的函数中它确实会显示数据。

我的目标是在服务中拥有一些功能 getStuff(),可由应用程序在 ngOnInit 调用,具有下拉菜单和内容的值

见过 this 但没能帮助找出问题所在

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

在安排 http.get(...) 调用后 console.log(this._data) 将被执行。这是在对服务器的调用甚至启动之前。

http.get(...) 调用也仅在 http.get(...) 返回的可观察对象被订阅时安排,因为可观察对象是惰性的。

使用 map(...) 而不是 subscribe(...) returns 和 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)
  }
}

在一个组件中你可以像这样使用它

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

另见

这样您就可以在实例化服务时就已经发起对服务器的调用,而不仅仅是在使用该服务的组件订阅之后。