首页 > 解决方案 > 角 HTTP GET

问题描述

  1. 我有一个在“localhost:3000”上运行的服务器。它将数据显示为 JSON,例如“localhost:300/locations”。
  2. 我的“data.service.ts”包括以下代码:

path: string = 'http://localhost:3000'
constructor(private http: HttpClient) { }

// Locations
getAllLocations(): Observable<Location[]> {
  let location = null;
  this.http.get(this.path + '/locations')
    .map((res => location = res))
    .catch((error: any) => Observable.throw(console.log(error)));
  return location;
}

  1. 在我的 result.component.ts 中,我正在运行以下代码:

constuctor(private dataservice: DataService) { }

ngOnInit() {
  console.info(this.dataservice.getAllLocations());
}

我期望将所有位置作为 JSON 的输出,而不是输出为“null”。

有人对如何使其正常工作有任何建议吗?

更新:还尝试了 HTTP 调用:

getAllLocations(): Observable<Location[]> {
  this.http.get<Location[]>(this.path + '/locations')
    .pipe(
      tap(items => console.info('fetched items'))
    );  
}
不幸的是,这段代码的输出是:“Object { _isScalar: false, source: {...}, operator: {...} }”

标签: jsonangulartypescript

解决方案


您必须从服务中返回 Observable:

path: string = 'http://localhost:3000'
constructor(private http: HttpClient) { }

// Locations
getAllLocations(): Observable<Locations[]> {
  return this.http.get(this.path + '/locations')
    .map((res => location = res))
    .catch((error: any) => Observable.throw(console.log(error)));
}

并在组件中订阅它。

constructor(private dataservice: DataService) { }

ngOnInit() {
  this.dataservice.getAllLocations().subscribe(result => {
      console.log(result);
   })
}

推荐阅读