Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Http 使用Angular 2中服务的Json文件_Http_Typescript_Angular_Observable - Fatal编程技术网

Http 使用Angular 2中服务的Json文件

Http 使用Angular 2中服务的Json文件,http,typescript,angular,observable,Http,Typescript,Angular,Observable,我有服务。 在构造函数中: 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 ) consol

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

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
返回
undefined
,尽管如果
console.log
被移动到传递给
subscribe
的函数中,它会显示数据

我的目标是在服务中有许多函数
getStuff()

看到但没有帮助找出错误所在

此.http.get('../assets/my_json_file.json')
是异步的,这意味着对服务器的调用将在稍后执行,当服务器的响应最终到达时,传递给
.subscribe(…)
的回调将随响应一起调用。“计划”是指在完成先前计划的任务后,将任务添加到事件队列中,以便稍后执行

在调度
http.get(…)
调用后,将执行
console.log(此.\u数据)
。这甚至是在对服务器的调用启动之前

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

使用
map(…)
而不是
subscribe(…)
返回一个
可观察的
而不是
订阅
,它允许服务用户将自己的代码链接到响应事件

@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));
  }
}
另见


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

您不能这样使用它。http是异步的,您希望使用它进行同步。您可以在服务中使用getStuff函数,但需要在数据准备就绪时开始调用这些函数,这只能通过在应用程序组件中使用另一个订户来实现。因此,json并不重要,数据是通过与服务器相同的http获取的。