Cannot access Injectable service in Angular2

In the angular2 application, there is a service named HttpClient. The purpose of this service is to include an authorization header in every request sent by the application to 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;
    }
}

Additonally, the service sets errors through 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);
    }
}

These services will be initialized in the main.ts file.

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

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

The goal now is to present errors in the header component. Whenever an error occurs, it should be displayed in a separate box within the header.

A challenge faced is that the method ErrorService.setError(error) inside HttpClient.handleError does not trigger as expected.

Answer №1

To maintain the scope of 'this', you should write:
.catch((e) => this.handleError(e));

where '(e)' represents the parameter list.

Another option is to use:
.catch(this.handleError.bind(this));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide on developing a custom object type, with keys that are derived from the values in the original object

I'm attempting to transform an object into a dynamically created type, but I'm having difficulty getting it to work correctly. Imagine I have the following object: const constants = { filter: 'flr', color: 'col' } Is ...

Issue with react router v6: Component fails to render even though route has been changed

The router seems to be experiencing an issue where it does not render a component. Specifically, on the home page, the Private Route is only rendered once. Clicking on a NavLink changes the URL to "/agreements", but the component itself is not being render ...

Implementing an overlay feature upon clicking a menu item - here's how!

I am currently working on implementing an overlay that displays when clicking on a menu item, such as item 1, item 2 or item 3. I have managed to create a button (Click me) that shows an overlay when clicked. Now, I would like to achieve the same effect wh ...

Cucumber Wrangler

I am completely new to using protractor/cucumber and restler in Typescript. The code below is what I have so far for hitting an endpoint URL and getting the response: Given('Hit the {string}', async (string) => { browser.quit() var data: ...

What is the reasoning behind ethers.js choosing to have the return value of a function be an array that contains the value, rather than just the value itself

An issue arose with the test case below: it('should access MAX_COUNT', async () => { const maxCount = await myContract.functions.MAX_COUNT(); expect(maxCount).to.equal(64); }); The test failed with this error message: ...

Troubleshooting Cors Problem between Angular 2 Form Data and Express

I'm attempting to send some files to an Express server that utilizes the cors() module in the following way app.use(cors()); This is the Angular 2 code used for file uploading let formData:FormData = new FormData(); for(let i = 0; i < files. ...

A static factory method within an abstract class

I am currently developing a class system using Typescript. The main structure consists of an abstract class called Component, which includes a static method called create(). This method is utilized on child classes to generate specific instances. abstract ...

I encountered a problem where the error "Type '(err: Error) => void' does not possess any properties similar to type 'QueryOptions'" appeared, and I am unsure of the underlying cause

Check out my route for removing a user: https://i.stack.imgur.com/fevKI.png I've set up a route called "/deleteuser" that uses the POST method. It validates the request body for an id and then proceeds to delete the user with that ID from the databas ...

Pass information captured from Mat Dialog up to the main component

Looking for a way to pass true/false boolean data from a dialog box into the parent component without just console logging the result? You want to store it in a variable in the parent component for further use. Any suggestions on how to achieve this? This ...

Issues with typescript compiler when using React-beautiful-dnd

I recently updated react and react-beautiful-dnd to the newest versions and now I am encountering many type errors in my code: {sortedDimensions.map((dimension: any, index: number) => ( <Draggable key={index} ...

Angular 13: SyntaxError Encountered: Token 'export' Not Recognized

After upgrading Angular from version 12 to 13, I encountered an error when running the app: "Uncaught SyntaxError: Unexpected token 'export'." Here are some additional details for context: In the angular.json configuration file, I had specified ...

Empty nested Map in POST request

I am currently working on a springboot application with a React/Typescript frontend. I have defined two interfaces and created an object based on these interfaces. export interface Order { customer_id: number; date: Date; total: number; sp ...

Obtain keys from an object implemented with an interface in TypeScript

Is it possible to retrieve the actual keys of an object when utilizing an interface to define the object? For example: interface IPerson { name: string; } interface IAddress { [key: string]: IPerson; } const personInAddressObj: IAddress= { so ...

What steps can I take to avoid an invalid operation on a potentially null reference in typescript?

Take a look at this scenario where the variable a can potentially be null, and is explicitly defined as such. Even when strict null checks are enabled, TypeScript does not flag a possible issue in this situation - let a: string | null = "hello" function ...

React hook triggering re-render

A function has been implemented to retrieve and decode user claims from a token stored in local storage using a hook. export const useActiveUser = (): { user: IUserTokenClaims | null } => { const [user, setUser] = useState<IUserTokenClaims | nul ...

Deciphering Route Parameters within Angular 2

Recently diving into Angular 2, I stumbled upon this resource, which details various methods for creating route links. 1. <a [routerLink]="[ '/path', routeParam ]"> 2. <a [routerLink]="[ '/path', { matrixParam: 'value&ap ...

Looking to start using WebDriverIO and Typescript with the WDIO wizard? Here's how to get it

I'm in the process of setting up a WebdriverIO project using TypeScript and Cucumber. I followed the steps provided by the wizard, which was pretty straightforward. I opted for Cucumber, TypeScript, and the page object model. This setup created a tes ...

Do we need to import Vue in every component when using Nuxt with TypeScript?

I recently integrated TypeScript into Nuxt using the guidelines provided in the documentation: However, I have a specific question regarding component setup. Should I always include import vue from "vue" and export default Vue.extend ({}); in al ...

A guide on altering the color of a badge through programming

I am curious to learn how I can dynamically change the color of a badge in Angular. My goal is to initially set the color of the badge to white, and then if the percVLRiskTotal reaches a specific value, change the color to green as an example. CSS: <sp ...

Using computed properties with Nuxt's `head` property can result in error messages being displayed

While utilizing Nuxt.js, I am using head() { } method to configure SEO metadata. However, when accessing computed properties within this method, Vetur displays the following message: Property 'domain' does not exist on type 'CombinedVueInst ...