我正在为我的完整堆栈应用程序构建一个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
. 即char的errMsg char . 如何以一个完整的字符串返回?
2 回答
哟可能不会返回JSON . 您正在使用String进行响应,并期待JSON .
在你的回复代码中做这样的事情..
运算符
catch()
将一个回调作为参数,该回调必须返回一个新的Observable,以下Observer将重新订阅并继续 .你从回调函数返回只是一个字符串
errMsg
所以你的代码等同于:哪个打印到控制台because of subscribeToResult() is used internally:
观看现场演示:http://plnkr.co/edit/HODmdrNqRrw5ctSICktj?p=preview
如果要在组件中接收错误,则需要重新抛出错误,并在
subscribe()
方法上使用onError
handler:请注意,在Angular2中,您使用的是RxJS 5,其文档中还没有
catch()
方法,因此如果您阅读RxJS 4的原始文档,它可能会有不同的表现 .