首页 > 解决方案 > 使用 Angular 链接的服务端点

问题描述

我有以下 DataService,它应该在链中调用以下 API,因此我能够将前一个的响应传递给下一个。到目前为止,这就是我开始的方式,但是当我尝试访问响应对象的属性之一时出现以下错误:

为什么会发生这种情况,因为当我 console.log 响应时,它具有以下结构:

{
  "data": "",
  "id": ""
}

“对象”类型上不存在属性“数据”。

import { Injectable } from '@angular/core';
import { Person } from './entities/person';
import { HttpClient } from '@angular/common/http';
import 'rxjs/add/operator/toPromise';
import { mergeMap } from '../../node_modules/rxjs/operator/mergeMap';
import { Observable } from '../../node_modules/rxjs/Observable';

@Injectable()
export class DataService {
  results: Person[];
  apiUrl1: string = 'http://localhost:3000/person/';
  apiUrl2: string = 'http://localhost:3000/facility';
  apiUrl3: string = 'http://localhost:3000/exposure';

  constructor(private http: HttpClient) {
  }

  createPerson(person: Person): Observable<any> {
    return (this.http.post(this.apiUrl1, person)
    .map(response => this.http.post(this.apiUrl2, response.data)));
  }

标签: angularhttpresponsechaining

解决方案


Typescript 严格检查响应中的数据属性,只需将响应类型更改为 any,

.map((response : any) => this.http.post(this.apiUrl2, response.data)));

推荐阅读