首页 > 解决方案 > 从 Observable 获取数据的建议

问题描述

我创建了一个执行 http 请求的 ServiceHttpWrapper,响应被打包到一个 observable 中,但是如何在变量中获取响应的数据?

HttpWrapper:

public get(params: HttpParams): Observable<any> {
    let { apiUrl } = this.configRequest(params.slugType, params.slug);

    return fromPromise(this._apiBase.get(apiUrl, params.payload)) //payload change
      .pipe(map(res => ({
        type: params.successActionType,
        payload: res
      })),
      catchError(res => of({
        type: params.errorActionType,
          action_type: params.specificErrorType,
          payload: {
            message:  res.response
          }
      })));
  }

_apiBase.get() 基本上是一个 axios.get 请求。

通过以下方式输出请求:

 productApi.getProductByID('2').subscribe((data) => {
    console.log(data);
  });

控制台输出

payload:
   { status: 200,
     statusText: 'OK',
     headers:
      { date: 'Thu, 25 Jul 2019 13:18:35 GMT',
        'content-type': 'application/json; charset=utf-8',
        'content-length': '509',
        connection: 'close',
        'set-cookie': [Array],
        'x-powered-by': 'Express',
        vary: 'Origin, Accept-Encoding',
        'access-control-allow-credentials': 'true',
        'cache-control': 'public, max-age=14400',
        pragma: 'no-cache',
        expires: 'Thu, 25 Jul 2019 17:18:35 GMT',
        'x-content-type-options': 'nosniff',
        etag: 'W/"1fd-XTG63SYhaP/Uo6/vgmARnL3rpBk"',
        via: '1.1 vegur',
        'cf-cache-status': 'HIT',
        age: '4336',
        'accept-ranges': 'bytes',
        'expect-ct':
         'max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"',
        server: 'cloudflare',
        'cf-ray': '4fbe6bb26d0bc2c2-FRA' },
     config:
      { url: 'https://jsonplaceholder.typicode.com/users/2',
        method: 'get',
        ....
        data: undefined },
     request:
      ClientRequest {         
        ....            
        ...,
     data:
      { id: 2,
        name: 'Ervin Howell',
        username: 'Antonette',
        email: 'Shanna@melissa.tv',
        address: [Object],
        phone: '010-692-6593 x09125',
        website: 'anastasia.net',
        company: [Object] } } }

标签: reactjsaxioshttprequest

解决方案


推荐阅读