Angular 4 - 将服务中的err对象捕获到组件
问题描述:
我正在使用角度为前端和弹簧安全性作为后端的登录页面,似乎一切正常,但是当我尝试处理通过从服务捕获到组件的错误不起作用。Angular 4 - 将服务中的err对象捕获到组件
service.ts
login(form) {
var objectToSend = 'j_username=' + form.j_username + '&j_password=' + form.j_password;
const headers = new Headers(
{
'Content-Type': 'application/x-www-form-urlencoded',
}
);
const options = new RequestOptions({headers: headers, withCredentials: true});
return this.http.post('http://localhost:8080/***********/authenticate', objectToSend, options)
.map((res) => res)
.catch((error: any) => {
if (error.status === 401) {
console.log(error.status + ' is the current status');
return Observable.throw(new Error(error.status));
} else if (error.status === 400) {
return Observable.throw(new Error(error.status));
} else if (error.status === 409) {
return Observable.throw(new Error(error.status));
} else if (error.status === 406) {
return Observable.throw(new Error(error.status));
}
});
}
login.component.ts
loginProcess() {
this._authenticationService.login(this.form.value).subscribe(
res => {
this.data = res;
if (res.status === 200) {
this._authenticationService.getRoles().subscribe(
resp => {
if (resp.status === 200) {
this.roles = JSON.parse(resp.text());
this.role = this.roles[0].authority;
localStorage.setItem('role', this.role);
this.connectedUser.eusLogin = this.form.value.j_username;
this.saveConnectedUser(this.connectedUser);
this.updateSessionTimeOut();
if (this.role === 'ROLE_ADMIN') {
this._router.navigate(['home']);
}
} else {
this.showErrorMsgDetail = true;
this.error = true;
}
},
error => {
this.error = true;
}
);
} else {
}
},
err => {
if (err.status === 401) {
this.showErrorMsgDetail = true;
this.errorMsgDetail = 'Bad credentials, try again';
}
}
);
}
的问题是在捕捉从服务到该组件的响应代码,在组件级别ERR .status未定义。
希望你们能弄清楚这一点。
答
您试图在没有任何Event Emitter或BehaviorSubject的情况下进行通信,您希望如何在其他位置捕获错误?
您必须在服务中发现错误,将其注入到构造函数中的登录组件中,然后您只需使用this.myService.getDataFromWebService(post)从组件中调用您的服务。
getDataFromWebService(postData: Kpi): EventEmitter<Kpi> {
const event: EventEmitter<Kpi> = new EventEmitter();
this.sendPost(myService.API_PATH, postData).subscribe((data) => {
try {
if (this.checkError(data)) {
const parseData: Kpi = Kpi.parse(data);
event.emit(parseData);
} else {
event.emit(new Kpi());
}
} catch (ex) {
this.env.error("Unknown error", "Invalid data received");
console.log("Exception", ex);
kpiEvent.emit(new Kpi());
}
});
return event;
}
你能展示更多的组件代码吗? – DeborahK