George Edwards George Edwards - 1 month ago 10
TypeScript Question

Angular2 Observable in http service returning errors char by char

I am building an angular2 front end for my full stack application. I am working on user login and I have this function which is called when the login form is submitted:

onSubmit(email, password) {
this.userService.login(this.user.email, this.user.password).subscribe((result) => {
console.log('reps' + result)
if (result) {
this.router.navigate(['']);
}
});
}


The login function in my userService is as follows:

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);
}


and finally, the handleError function:

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;
}


When I submit the wrong password, I get the error:


401 - Unauthorized Response with status: 401 Unauthorized for URL: http://localhost:3000/api/login


printed from the
errMsg
variable in my error handler. This is great, however, back in my component, I then get
resp4
,
resp0
,
resp1
... printed out. i.e. the errMsg char by char. How can I get this to return in one full string?

Answer

Yo are prob not returning JSON. You are prob responding with a String and it is expecting JSON.

do something like this in your response code ..

let json = JSON.parse(str);
res.send(json); // responding with parsed JSON