Ionic Angular:为什么我会得到一个Observable作为resonse

hgtggwj0  于 11个月前  发布在  Ionic
关注(0)|答案(1)|浏览(99)

我得到了一个意外的Observable(假设是随机的)作为响应res(预期结果是一个对象数组):

this.api[op.type](op.endpoint,op.body, op.token).pipe(
        take(1),
        tap(async res=>{
          try{            
            if (res){ //getting Observable here
              //do something with res
            }
          }catch(err){
            console.log(err)
          }
          
        }),
        catchError(async (err)=>{
            //more error handling          
        })

字符串
我的api['post']是这样的:

post(endpoint: string, body: any, token? : string, reqOpts?: any, url_alt?: any) {
    this.set_headers(token);
    if (!reqOpts) reqOpts = {};
    this.headers.append({"Content-Type": "application/json"});
    reqOpts.headers = this.headers;
      return this.http.post(this.url + endpoint, body, reqOpts).pipe(
        timeout(105000),
        retry(3),
        catchError(async (error)=>{
          return throwError(error)
        })
  
      );
    }
  }


如果你能告诉我这里出了什么问题,

k10s72fa

k10s72fa1#

在post的catchError块中,当我在Observable函数返回之前添加了blog c时,blog c行是有问题的,否则它工作得很好!
服务

import { Injectable } from '@angular/core';
import { of, retry, take, throwError, timeout } from 'rxjs';
import { catchError, tap } from 'rxjs/operators';

@Injectable({
  providedIn: 'root',
})
export class TestService {
  constructor() {}

  post(
    endpoint: string,
    body: any,
    token?: string,
    reqOpts?: any,
    url_alt?: any
  ) {
    // this.set_headers(token);
    if (!reqOpts) reqOpts = {};
    // this.headers.append({"Content-Type": "application/json"});
    // reqOpts.headers = this.headers;
    return throwError('test') // this.http.post(this.url + endpoint, body, reqOpts) // mock http call!
      .pipe(
        timeout(105000),
        retry(3),
        catchError((error) => { // <-- this line is the problem, when I add async before the function Observable gets returned, else it works fine!
          return of(error);
        })
      );
  }

  postWrapper() {
    return this.post('', null).pipe(
      take(1),
      tap(async (res) => {
        try {
          console.log('tap', res);
          if (res) {
            //getting Observable here
            //do something with res
          }
        } catch (err) {
          console.log('catch', err);
        }
      }),
      catchError(async (err) => {
        return of(err);
        //more error handling
      })
    );
  }
}

字符串
stackblitz

相关问题