1
votes

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?

2

2 Answers

0
votes

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
1
votes

Operator catch() takes as a parameter a callback that has to return a new Observable that is where the following Observer will resubscribe and continue.

You're returning from the callback just a string errMsg so your code is equivalent to this:

Observable.create(obs => {
        obs.next('r1');
        obs.next('r2');
        obs.next('r3');
        obs.error('error');
    })
    .catch(val => val)
    .subscribe(val => console.log(val));

Which prints to console because of subscribeToResult() is used internally:

r1
r2
r3
e
r
r
o
r

See live demo: http://plnkr.co/edit/HODmdrNqRrw5ctSICktj?p=preview

If you want to receive the error in the component you need to rethrow the error and than use also onError handler on the subscribe() method:

...
.catch(val => {
    throw val;
})
.subscribe(
    val => console.log(val),
    val => console.log('Error:', val)
);

Note, that in Angular2 you're using RxJS 5 and its catch() method is not present in the documentation yet, so if you read the original doc for RxJS 4 it might behave differently.