【问题标题】:Check type of object returned by Observable in Angular?检查 Angular 中 Observable 返回的对象类型?
【发布时间】:2020-11-25 16:50:38
【问题描述】:

我正在制作一个向 API 发送调用的 Angular 应用程序。这是来自 AuthService 的方法之一(负责对用户进行身份验证):

login(loginForm: UserLoginRequest): Observable<AuthenticationResponse | TfaResponse> {
    return this.http.post<AuthenticationResponse | TfaResponse>('api/auth/login', loginForm);
}

此方法返回具有以下响应之一的 Observable:

export class AuthenticationResponse {
    token: string;
    refreshToken: string;
}

export class TfaResponse {
    requiresTwoFactor: boolean;
    isTwoFactorConfigured: boolean;
}

然后我在我的组件中订阅这个 Observable,我想根据响应类型执行不同的操作:

this.authService.login(userLoginForm)
    .subscribe(
      (result) => {
        // type of result is AuthenticationResponse
        if (*type check*) {
            // action with AuthenticationResponse
        }
        // type of result is TfaResponse
        else if (*type check*) {
            // action with TfaResponse
        }
      },
    );

目前我只是在检查对象是否拥有此类的某些属性,如下所示:

this.authService.login(userLoginForm)
        .subscribe(
          (result) => {
            if ('token' in result) {
                // action with AuthenticationResponse
            }
            else if ('requiresTwoFactor' in result) {
                // action with TfaResponse
            }
          },
        );

但我知道这绝对是一个糟糕的解决方案,它会在首次更改 AuthenticationResponse 或 TfaResponse 类后中断。在这种情况下我应该如何检查课程?

【问题讨论】:

  • Typescript“类型”在运行时不存在,您实际上并没有创建类实例,只是简单的 JS 对象。您将需要在您的响应中确定它是什么类型,天气这是一个额外的属性值,或者您正在检查服务器发回的属性(就像您现在所做的那样)。
  • 为什么你的服务返回两个完全不同的对象?你的根本问题是这个不稳定的合同
  • if ('token' in result) 对我来说似乎是一个完全可以接受的解决方案?虽然你真的应该使用hasOwnProperty 而不是in

标签: angular typescript class casting observable


【解决方案1】:

您可以使用 instanceof 关键字来检查类型。

if (result instanceof AuthenticationResponse) {
  .....
} else if (result instanceof TfaResponse) {
  .....
}

【讨论】:

  • 这些都将失败,因为 OP 只是将原始 JSON 解析为 Angular HttpClient 默认执行的普通对象,而不是实际创建类实例以检查 instanceof
猜你喜欢
  • 2018-11-12
  • 1970-01-01
  • 2011-07-09
  • 1970-01-01
  • 2017-10-12
  • 2019-06-25
  • 2021-10-06
  • 2019-05-14
  • 2019-11-18
相关资源
最近更新 更多