John Baird
John Baird

Reputation: 2676

Handling Observable errors in angular 2 servcie

I have a login service that calls an authorization service and I need to trap any errors coming back from the api server.

I currently have this in my login.component:

   loginUser() {
    console.log(this.localUser.email);
    console.log(this.localUser.password);

    this.loginService.loginUser(this.localUser)
        .subscribe(
        token => {
            console.log('token = ' + token)
            this.token = token},
        error => {
            this.errorMessage = <any>error
            console.log("err msg = " + this.errorMessage);
        },
        () => this.completeLogin());
}

this is my login service:

loginUser(localUser: LocalUser) {
    return this.authorizationService.loginUser(localUser);
}

and this as my auth service:

loginUser(localUser: LocalUser): Observable<Token> {
    var grantString: string = "grant_type=password&username=";
    var passwordString : string = "&password="
    var email = localUser.email;
    var password = localUser.password;

    var headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');

    var creds:string = grantString + email + passwordString + password;

    return this.http.post(this.url, creds, { headers: headers })
        .retry(2)
        .timeout(20000, new Error('Timeout expired.'))
        .delay(1000)
        .map((response: Response) => <Token>response.json())
        .catch(this.handleError);
}

handleError(error: any) {
    let errorMsg = error.message || 'Server error';
    console.error(errorMsg);
    return Observable.throw(errorMsg);
}

The problem is that the err message returned is not the server error, but this: "err msg = TypeError: Object doesn't support property or method 'throw'"

Any ideas on how to get the real message?

Upvotes: 2

Views: 2457

Answers (1)

magiccrafter
magiccrafter

Reputation: 5482

Most likely you are missing the import for rxjs 'throw' static.
That could happen if you import the rxjs operators and statics by yourself one by one.

// Statics
import 'rxjs/add/observable/throw';

For complete list check here:
https://github.com/ReactiveX/rxjs/blob/master/src/Rx.ts

Upvotes: 4

Related Questions