如何在 Angular 2 Typescript 中推送变量中的 Web 服务

How to push Web Service in Variable in Angular 2 Typescript

我想将动态 Web 服务数据推送到 app.service.ts 文件中的 TRACKONE

我在 link 上创建了一个服务器,它按照下面 Track[ ] 中显示的相同顺序投影 JSON。 =14=]

[
  {id: 11, name: 'App1'},
  {id: 12, name: 'App2'},
  {id: 13, name: 'App3'},
  {id: 14, name: 'App4'}
];

还使用 Http 从服务器获取数据并存储在函数中,该函数每 5 秒间隔获取数据并刷新数据并将其显示在 控制台.

private serviceUrl = "http://localhost:9000/service";

constructor(private http: Http){
  this.getService();
}

getServiceOne(interval: number): Observable<Track[]> {
  return Observable.timer(0,interval)
  .mergeMap(()=>{
    return this.http.get(this.serviceUrl)
      .map(res => res.json());
  });
}

getService() {
  this.getServiceOne(5000).subscribe(posts => {
    console.log(this.posts = posts);
  })
}

我只需要将 JSON 值从 getService() 传递到 export var TRACKONE: Track[ ]

export class Track {
  id: number;
  name: string;
}

export var TRACKONE: Track[] = [
  {id: 11, name: 'App1'},
  {id: 12, name: 'App2'},
  {id: 13, name: 'App3'},
  {id: 14, name: 'App4'},
];

请帮助找到正确的解决方案。提前致谢。

最后我弄明白了,我需要在组件中而不是在服务中调用 getServiceOne( ) 函数,因为我遇到了这个问题。

现在我在 component.ts 文件中添加了以下行并导入了 service.ts 文件,它是工作正常。

getTrackOnes(): void {
  this.trackoneService.getServiceOne(5000).subscribe(tracks => {this.tracks = tracks;});
}