【问题标题】:Service endpoints chaining with Angular使用 Angular 链接的服务端点
【发布时间】:2018-07-08 12:43:27
【问题描述】:

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

【问题讨论】:

    标签: angular httpresponse chaining


    【解决方案1】:

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

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

    【讨论】:

    • 感谢已修复,但未将数据发布到第二个 api。
    • 您需要在网络选项卡上检查并调试它。标记是否有帮助
    • @CodeWorm 您可能想尝试使用flatMap 而不是map
    【解决方案2】:
    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
            });
        });
    }
    

    【讨论】:

    • Observables 没有then 函数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多