我有一个应用程序,当用户登录时,他收到了一些数据作为响应,但是如果响应不是我所期望的,则该应用程序崩溃。
让我向您展示以下内容:
我创建了一个接口来告诉Typescript我期望的数据。
export interface AuthResponseData {
token: string;
expires: string;
role: number;
}
然后,我创建了一种将登录数据发送到服务器的方法。
login(user: string, password: string){
return this.http.post<AuthResponseData>(
'https://localhost:44344/api/auth', { user: user, pwd: password }
).pipe(
catchError(this.handleError),
tap(resData => { this.handleAuthentication(resData.token, resData.expires, resData.role)})
);
}
我期望,如果服务器的响应与接口不匹配,则Angular将重定向到catchError。但是不会发生。
现在我的问题是:有什么方法可以检查API响应是否等于接口,如果不是,则抛出错误。还是我要问的是不可能的?
UPDATE:
搜索后,我发现接口在运行时消失了,因此,就我所知,没有办法将api响应与接口进行比较。但我一直在寻找一种以动态方式检查api响应的方法。我认为根据api的响应始终正确并不真正安全。因此,我应该检查API响应。我该怎么办?
希望您能帮助我,谢谢:)
您可能会抛出catchError()
会捕获的错误
login(user: string, password: string){
return this.http.post<AuthResponseData>(
'https://localhost:44344/api/auth', { user: user, pwd: password }
).pipe(
map(res => { // Map should return an observable
if(!this.isValid()) // isValid() is a hole diffrent story - stucture checking in tyepscript -
throw new Error('Response structure is not valid.') // Would be catched by catchError
return res;
})
tap(resData => { // tap is for side effects
this.handleAuthentication(resData.token, resData.expires, resData.role)
})
catchError(this.handleError)
);
}
现在为响应结构,您可以检查Interface type check with Typescript
要检查API响应是否有效,请使用类而不是接口并为其提供isValid
函数,和/或检查构造函数中的数据。
例如
interface IAuthResponseData {
token: string;
expires: string;
role: string;
}
class AuthResponseData implements IAuthResponseData {
public token: string;
public expires: string;
private __expires: Date;
public role: string;
public constructor(data: IAuthResponseData) {
this.token = data.token;
this.expires = data.expires;
this.__expires = new Date(data.expires);
this.role = data.role;
if (!this.isValid()) {
throw new Error("Invalid Parameters")
}
}
public isValid(): boolean {
// simple equals check against null is also true when the value is undefined
for (let member in this) {
if (this[member] == null) {
return false;
}
}
return true;
}
}
请记住要捕获错误并对其执行操作,或者将校验留在构造函数之外,而是在创建对象之后再对其进行检查。
您可以使用instanceof检查响应的类型,并使用rxjs throwError抛出错误以防错误
import { throwError} from 'rxjs';
...
login(user: string, password: string){
return this.http.post<AuthResponseData>(
'https://localhost:44344/api/auth', { user: user, pwd: password }
).pipe(
tap(resData => {
if(resData instanceof AuthResponseData) {
this.handleAuthentication(resData.token, resData.expires, resData.role)
} else {
throwError(new Error('Invalid response!'))
}
}),
catchError(this.handleError),
);
}