服务端点与Angular链接

时间:2018-07-08 12:43:28

标签: angular httpresponse chaining

我有以下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)));
  }

2 个答案:

答案 0 :(得分:1)

Typescript严格检查响应中的data属性,只需将响应类型更改为任意,

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

答案 1 :(得分:0)

createPerson(person: Person): Observable<any> {
    return this.http.post(this.apiUrl1, person)
    .subscribe(response => {
        // do whatever you wanna do :
        this.http.post(this.apiUrl2, response.data)
        .subscribe(response2 => {
            // continue like this
        });
    });
}