Angular:为什么我得到一个 Observable 作为响应

问题描述 投票:0回答:1

我得到了一个意外的 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)
        })
  
      );
    }
  }

非常感谢有关此处问题的任何指导

angular ionic-framework
1个回答
0
投票

异步行是

catchError
帖子块中的问题,当我在函数 Observable 返回之前添加异步时,否则它工作正常!

服务

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
      })
    );
  }
}

堆栈闪电战

© www.soinside.com 2019 - 2024. All rights reserved.