如果 Angular2 HTTP 响应数据不符合类型,我如何捕获错误
How do I capture error if Angular2 HTTP response data does not adhere to type
如果我使用类型创建一个 Angular2 HTTP 请求,然后也分配一个具有特定类型的响应,如果服务器响应不是该类型,那么我可以捕获错误而不是破坏应用程序并执行 activity?
.....接口.....
export interface loginUser {
username: string;
password: string;
}
export interface loginResData {
username: string;
details: string;
}
...组件代码.....
user: loginUser
constructor(private _httpprovider: Httpprovider, private _router: Router) {
}
login(user) {
this._httpprovider.httpReq(this.url, 'POST', user, null).subscribe((data: loginResData) => {
this.loginEvent.emit(data);
});
}
如何捕获发生在数据上而不是类型数据上的错误:loginResData。首先有可能吗?
接口在运行时被忽略。你最好创建一个 class like
export class loginResData {
username: string;
details: string;
constructor(data:any) {
if(data && data.username && data.details) {
this.username = data.username;
this.details = data.details;
}
throw 'loginResData is invalid or incomplete';
}
}
login(user) {
this._httpprovider.httpReq(this.url, 'POST', user, null)
.map(data:any => new oginResData(data))
.subscribe((data: loginResData) => {
this.loginEvent.emit(data);
});
}
如果我使用类型创建一个 Angular2 HTTP 请求,然后也分配一个具有特定类型的响应,如果服务器响应不是该类型,那么我可以捕获错误而不是破坏应用程序并执行 activity?
.....接口.....
export interface loginUser {
username: string;
password: string;
}
export interface loginResData {
username: string;
details: string;
}
...组件代码.....
user: loginUser
constructor(private _httpprovider: Httpprovider, private _router: Router) {
}
login(user) {
this._httpprovider.httpReq(this.url, 'POST', user, null).subscribe((data: loginResData) => {
this.loginEvent.emit(data);
});
}
如何捕获发生在数据上而不是类型数据上的错误:loginResData。首先有可能吗?
接口在运行时被忽略。你最好创建一个 class like
export class loginResData {
username: string;
details: string;
constructor(data:any) {
if(data && data.username && data.details) {
this.username = data.username;
this.details = data.details;
}
throw 'loginResData is invalid or incomplete';
}
}
login(user) {
this._httpprovider.httpReq(this.url, 'POST', user, null)
.map(data:any => new oginResData(data))
.subscribe((data: loginResData) => {
this.loginEvent.emit(data);
});
}