http服务中的Angular2 Observable按字符返回错误
Angular2 Observable in http service returning errors char by char
我正在为我的全栈应用程序构建一个 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 - Unauthorized Response with status: 401 Unauthorized for URL: http://localhost:3000/api/login
从我的错误处理程序中的 errMsg
变量打印。这很好,但是,回到我的组件中,然后打印出 resp4
、resp0
、resp1
...。即 errMsg char by char。我怎样才能在一个完整的字符串中得到这个 return?
Operator catch()
将回调作为参数,该回调必须 return 一个新的 Observable,后续 Observer 将在其中重新订阅并继续。
你 return 从回调中得到的只是一个字符串 errMsg
所以你的代码等同于:
Observable.create(obs => {
obs.next('r1');
obs.next('r2');
obs.next('r3');
obs.error('error');
})
.catch(val => val)
.subscribe(val => console.log(val));
打印到控制台 because of subscribeToResult()
is used internally:
r1
r2
r3
e
r
r
o
r
观看现场演示:http://plnkr.co/edit/HODmdrNqRrw5ctSICktj?p=preview
如果您想在组件中接收错误,您需要重新抛出错误,而不是在 subscribe()
方法上使用 onError
处理程序:
...
.catch(val => {
throw val;
})
.subscribe(
val => console.log(val),
val => console.log('Error:', val)
);
请注意,在 Angular2 中,您使用的是 RxJS 5,其 catch()
方法尚未出现在文档中,因此如果您阅读 RxJS 4 的原始文档,它的行为可能会有所不同。
你很可能不会回来 JSON。您可能会用一个字符串响应,并且它期望 JSON.
在你的响应代码中做这样的事情..
let json = JSON.parse(str);
res.send(json); // responding with parsed JSON
我正在为我的全栈应用程序构建一个 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 - Unauthorized Response with status: 401 Unauthorized for URL: http://localhost:3000/api/login
从我的错误处理程序中的 errMsg
变量打印。这很好,但是,回到我的组件中,然后打印出 resp4
、resp0
、resp1
...。即 errMsg char by char。我怎样才能在一个完整的字符串中得到这个 return?
Operator catch()
将回调作为参数,该回调必须 return 一个新的 Observable,后续 Observer 将在其中重新订阅并继续。
你 return 从回调中得到的只是一个字符串 errMsg
所以你的代码等同于:
Observable.create(obs => {
obs.next('r1');
obs.next('r2');
obs.next('r3');
obs.error('error');
})
.catch(val => val)
.subscribe(val => console.log(val));
打印到控制台 because of subscribeToResult()
is used internally:
r1
r2
r3
e
r
r
o
r
观看现场演示:http://plnkr.co/edit/HODmdrNqRrw5ctSICktj?p=preview
如果您想在组件中接收错误,您需要重新抛出错误,而不是在 subscribe()
方法上使用 onError
处理程序:
...
.catch(val => {
throw val;
})
.subscribe(
val => console.log(val),
val => console.log('Error:', val)
);
请注意,在 Angular2 中,您使用的是 RxJS 5,其 catch()
方法尚未出现在文档中,因此如果您阅读 RxJS 4 的原始文档,它的行为可能会有所不同。
你很可能不会回来 JSON。您可能会用一个字符串响应,并且它期望 JSON.
在你的响应代码中做这样的事情..
let json = JSON.parse(str);
res.send(json); // responding with parsed JSON