【发布时间】:2017-03-07 06:07:51
【问题描述】:
我正在为我的全栈应用程序构建一个 angular2 前端。我正在处理用户登录,我有这个在提交登录表单时调用的函数:
onSubmit(email, password) {
this.userService.login(this.user.email, this.user.password).subscribe((result) => {
console.log('reps' + result)
if (result) {
this.router.navigate(['']);
}
});
}
我的userService中的登录功能如下:
login(_email, _password) {
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
let data = { email: _email, password: _password };
console.log(data);
return this.http.post('/api/login', data, options)
.map(this.extractData)
.map((res) => {
console.log('res' + JSON.stringify(res))
if (res.token) {
localStorage.setItem('auth_token', res.token);
this.loggedIn = true;
}
return true;
}).catch(this.handleError);
}
最后是handleError函数:
private handleError(error: Response | any) {
// In a real world app, we might use a remote logging infrastructure
console.log('isinError Handler' + error);
let errMsg: string;
if (error instanceof Response) {
const err = error || JSON.stringify(error);
console.log('err' + err); // Prints out "Response with status: 401 Unauthorized for URL: http://localhost:3000/api/login"
errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
} else {
errMsg = error.message ? error.message : error.toString();
}
console.error('msg' + errMsg); // Prints out "401 - Unauthorized Response with status: 401 Unauthorized for URL: http://localhost:3000/api/login"
return errMsg;
}
当我提交错误的密码时,我得到了错误:
401 - 未经授权的响应,状态为:401 未经授权的 URL:http://localhost:3000/api/login
从我的错误处理程序中的errMsg 变量打印。这很好,但是,回到我的组件中,然后我得到resp4,resp0,resp1... 打印出来。即 errMsg char by char。我怎样才能让它以一个完整的字符串返回?
【问题讨论】:
标签: angular typescript rxjs rxjs5 angular2-http