我一直不知道如何输入我的HttpResponse.我试图匹配我的API返回给我的内容,但Vim中的打字帮助一直告诉我:

typescript: Type 'Observable<unknown>' is not assignable to type 'Observable<string | HttpErrorResponse>'.
  Type 'unknown' is not assignable to type 'string | HttpErrorResponse'. [2322]

我的帖子是这样的:

forgotPassword(args: {studentId: string, emailAddress: string}): RxObservable<HttpErrorResponse | string> {
  const body = {
    studentId: args.studentId,
    emailAddress: args.emailAddress
  }
    console.log("forgot password", body)

    return this.http
      .post<HttpErrorResponse | string>(
        `${this.nextApiEndpoint}Authentication/ForgotPassword`,
        body,
        {}
      )
      .pipe(
        switchMap((data: string) => data),
        catchError((err) => {
          return err;
        })
      );
  }

我正在try 使用SwitchMap来确保管道输出的数据是字符串,但我真的不需要这样做,因为这就是我的http响应已经是字符串.

推荐答案

您只需从帖子中删除HttpErrorResponse,并让catchError包含类型HttpErrorResponse!另外,因为我们不会使用以前的数据调用另一个API调用,所以我将switchMap换成了map

总而言之,我们不需要为HttpErrorResponse添加额外的行,只要成功返回类型就足够了,而TypeScrip将允许这一点!

import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';
import { catchError, map } from 'rxjs/operators';

@Injectable()
export class TestService {
  nextApiEndpoint = 'google.com';
  constructor(private http: HttpClient) {}

  forgotPassword(args: {
    studentId: string;
    emailAddress: string;
  }): Observable<string> {
    const body = {
      studentId: args.studentId,
      emailAddress: args.emailAddress,
    };
    console.log('forgot password', body);

    return this.http
      .post<string>(
        `${this.nextApiEndpoint}Authentication/ForgotPassword`,
        body,
        {}
      )
      .pipe(
        catchError((err: HttpErrorResponse) => {
          throw 'error in source. Details: ' + err.message;
        }),
        map((data: string): string => data)
      );
  }
}

Stackblitz Demo with no compilation errors

Angular相关问答推荐

Goto锚定在嵌套容器中,具有溢出自动

在Angular 17中加载页面时打开打印对话框

使Angular 效果只执行一次

如何在自定义验证器中获取所有表单控件(字段组动态创建)

PrimeNG面包屑组件生成奇怪的&

茉莉花-模板中调用了如何判断角管

MAT-复选框更改事件未在onSubscriberCheck函数中返回选中的值

列表和映射的SCSS语法

如何将参数传递给Angular 服务

一个接一个的Angular http请求,但只关心第一个

JsPDF Autotable 将图像添加到列中出现错误:属性getElementsByTagName不存在

Angular 按钮指令错误地附加子元素

Summernote 文本区域的输入字段文本验证失败

尽管模型中的变量发生了变化,但Angular 视图没有更新

如何在Angular2中基于特定的构建环境注入不同的服务?

为什么 Angular2 routerLinkActive 将活动类设置为多个链接?

AOT - Angular 6 - 指令 SomeComponent,预期 0 个参数,但go 有 1 个参数

Angular2 Routerlink:添加查询参数

路由 getCurrentNavigation 始终返回 null

如何在 Angular CLI 6: angular.json 中添加 Sass 编译?