Giorgi Pilishvili
Giorgi Pilishvili

Reputation: 91

catch error in http get

I'm trying to make http call and if there will be any error do my things.

Here is my code:

import { Injectable } from '@angular/core';

import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';

import 'rxjs/add/observable/throw';

// Operators
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/switchMap';
import 'rxjs/add/operator/toPromise';

@Injectable()
export class HttpCallService {

    constructor(private http: Http) { }

    getHeroes(): Observable<Hero[]> {
        console.log('entered');
        return this.http.get('Url')
            .map(this.extractData)
            .catch(this.handleError);
    }
    private extractData(res: Response) {
        console.log('extract entered');
        let body = res.json();
        return body.data || {};
    }
    private handleError(error: Response | any) {
        console.log('error entered');

        let errMsg: string;
        if (error instanceof Response) {
            const body = error.json() || '';
            const err = body.error || JSON.stringify(body);
            errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
        } else {
            errMsg = error.message ? error.message : error.toString();
        }
        console.error(errMsg);
        return Observable.throw(errMsg);
    }

}

export class Hero {
    constructor(
        public id: Date,
        public author: string,
        public text: string
    ) { }
}

When I call it it logs in console only entered which is in getHeroes. I know there will be error I haven't valid url but why it doesn't go to catch?

Upvotes: 0

Views: 390

Answers (1)

Yakov Fain
Yakov Fain

Reputation: 12376

You need to invoke the subscribe() method to make actual HTTP call. Your method getHeroes() just declares that it'll return the Observable when someone will subscribe to it. That's why you only see the log from getHeroes() - extractData() and handleErrors() are not even invoked.

You need to do getHeroes().subscribe() somewhere in your code.

Upvotes: 1

Related Questions