【发布时间】: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