0

I have a service in my angular2 app called HttpClient This service is supposed to add an authorization header to each request the application is sending to my endpoints.

import { Injectable }    from '@angular/core';
import { Headers, Http, Response, } from '@angular/http';

import { Router } from '@angular/router';

import { ErrorService } from '../../services/error/error.service'

@Injectable()
export class HttpClient {

    private token: string;
    private error: any;

    private webApi = 'http://localhost:8080/api/v1/';    // Url to web api

    constructor(
        private http: Http,
        private router: Router,
        private errorService: ErrorService) { }

    get(url: string): Promise<Response> {
        return this.http.get(this.webApi + url, this.createAuthorizationHeader())
                    .toPromise()
                    .catch((e) => this.handleError(e));
    }

    post(url: string, data: any): Promise<Response> {
        return this.http.post(this.webApi + url, JSON.stringify(data), this.createAuthorizationHeader())
                    .toPromise()
                    .catch((e) => this.handleError(e));
    }

    put(url: string): Promise<Response> {
        return this.http.get(this.webApi + url, this.createAuthorizationHeader())
                    .toPromise()
                    .catch((e) => this.handleError(e));
    }

    delete(url: string): Promise<Response> {
        return this.http.delete(this.webApi + url, this.createAuthorizationHeader())
                    .toPromise()
                    .catch((e) => this.handleError(e));
    }

    private handleError (error: any) {

        var status: number = error.status;

        if (status == 415) {
            this.errorService.setError(error);
        }

        let errMsg = (error.message)
            ? error.message
            : status
                ? `${status} - ${error.statusText}`
                : 'Server error';

        console.error(errMsg); // log to console instead
        return Promise.reject(errMsg);
    }

    private createAuthorizationHeader() {

        let headers = new Headers();
        headers.append('Content-Type', 'application/json');
        headers.append('Accept', 'application/json');

        if (localStorage.getItem('token'))
            this.token = localStorage.getItem('token');

        headers.append('Authorization', 'Bearer ' + this.token);

        return headers;
    }
}

Also this service is setting an error to another custom service called ErrorService

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

@Injectable()
export class ErrorService {

    error: any;

    public errorAdded$: EventEmitter<any>;

    constructor() {
        this.errorAdded$ = new EventEmitter();
    }

    getError(): any {
        return this.error;
    }

    setError(error: any) {
        alert('is not going to be called');
        this.error.error = error;
        this.errorAdded$.emit(error);
    }
}

Those services are going to be bootstrapped in my main.ts

...
import { ErrorService }   from './services/error/error.service';
import { HttpClient }   from './services/http/http.service';
...

bootstrap(AppComponent, [
    appRouterProviders,
    HTTP_PROVIDERS,
    ErrorService,
    HttpClient,
    ....
]);

Now I want to display this error in my header component. So overtime an error occurred this error is going to be displayed in a separated box in my header.

The Problem is that my ErrorService.setError(error) method called in HttpClient.handleError won't get even fired.

1 Answers1

2
.catch(this.handleError);

should be

.catch((e) => this.handleError(e));

to retain the scope of this. where (e) is the parameter list

Alternatively you can use

.catch(this.handleError.bind(this));
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567