Exploring Observable and Dependency Injection in Angular 2

I need help with a service that looks like this:

@Injectable()
export class AuthService {

    private contentHeader: Headers = new Headers({"Content-Type": "application/json", "Accept": "application/json"});   

    constructor(public events: Events, private authHttp: AuthHttp){

    }

    public get(url): Observable<any> {            
        return this.authHttp.get(url, { headers: this.contentHeader })
            .map(this.extractData)
            .catch(this.handleError);
    }


    public extractData(res: Response) {
        try {
            let body = res.json();
            return body || {};
        }
        catch (e) {
            return {};
        }
    }

    public handleError(error: any) {
        if (error.status == 401 || error.status == 403)
        {
            // injected
            this.events.publish('user:logout');
        }

        return Observable.throw(error);
    }

}

The issue is that this.events does not work inside of the handleError function and it triggers this error in the console: EXCEPTION: TypeError: this.events is undefined

Is there a way to use services with dependency injection within the map and catch sections of an Observable?

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

Angular 2 Encounter Error When Trying to Access Undefined Property in a Function

Element: import { Component, OnInit } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Component({ selector: 'app-ore-table', templateUrl: './ore-table.component.html', styleUrls: [&a ...

What is the alternative name for DOM elements in TypeScript?

When working with a HTMLImageElement, I can simply reference it like this: let image: HTMLImageElement; ... In Dart, importing the dom is possible using: import 'dart:html' as dom; Using 'dom' as an alias for the "dart:html" package. ...

There appears to be an issue with the compilation of the TypeScript "import { myVar }" syntax in a Node/CommonJS/ES5 application

In my Node application, I have a configuration file that exports some settings as an object like this: // config.js export var config = { serverPort: 8080 } Within another module, I import these settings and try to access the serverPort property: // ...

Angular 2 error: "HttpService Provider Not Found"

In my Angular 2 / Ionic 2 project, I have the following "constellation" of components and services: Component1 -> Service1 -> Service3 Component2 -> Service2 -> Service3 (where -> denotes a relationship like "using" or "calling") Whenever ...

What is the best way to append to an array if there is no response within 1 second?

I have a feature in my code that monitors requests and responses. I attempted to display a spinner only if a request takes more than 1 second: @Injectable() export class LoadingInterceptor implements HttpInterceptor { private requests: HttpRequest< ...

Troubleshooting: Issues with Angular 2 Cross-Domain Calls on Local Servers

My Angular 2 application is currently running on port 8100, while the API project built using Node and Express is running on a different port 3003. It is important to note that the API project is not a typical REST API. When attempting to call one of the ...

Come up with a multi-colored theme using angular material2 that features a palette of more than three

When customizing a theme for angular material2, it's mentioned that you can specify a primary, accent, warn foreground, and background color. However, the process for creating a theme only allows for 3 colors/palettes to be set: $candy-app-theme: ma ...

Hidden back navigation strategy in AngularJS 2 with location strategy

After creating a custom LocationStrategy to disable browser location bar changes, I am now looking to integrate smaller apps into various web pages without affecting the browser's location. While navigation works smoothly with this new strategy, I am ...

Adding foreign key values in Angular can be achieved through various methods. One common

In my database, I have a total of four tables. services: Contains columns - name, service_type (referencing id from service_type), channel_id (referencing id from channels), telco_id (referencing id from telco) service_type: Columns - id, name channel: C ...

Working with relative paths in React Native TypeScript using WebStorm

My variable color is located in the path app/theme. To set it up, I created a package.json file in app/package.json with the following content: { "name": "app" } Now, to import color in TypeScript files, I use the following syntax: import { color } fro ...

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 ...

Exploring the Possibilities of Utilizing Multiple Endpoints with Apollo Angular GraphQL

mywebsite.com/graphql/categories mywebsite.com/graphql/account mywebsite.com/graphql/connection I'm working with multiple GraphQL endpoints on my server, each one having its own mutations and queries. I want to create an Angular frontend for it bu ...

Exploring the child attributes of a component in Angular 2

I am currently working on a project involving Angular 2 and Ionic 2, and I need to retrieve a property from a parent component. The parent component is a class named "ServicesPage", while the child component is named "AddonCell". ServicesPage.html <i ...

"Encountered an issue while running the clean-css script in npm build

Encountering a peculiar error while running npm run build:prod today. "build:prod": "ng build --prod --aot=false --preserve-symlinks" The error message reads: 92% chunk asset optimizationC:\Projects\Latest_Feb26\ASSURE.OdyssEYGen2\Fr ...

Transform a specialized function into a generic function with static typing

First off, I have a network of routes structured like this: interface RouteObject { id: string; path: string; children?: RouteObject[]; } const routeObjects: RouteObject[] = [ { id: 'root', path: '/', children: [ ...

AgGrid:CellRenderer and Observables

Having trouble getting my backend data to display in the AGGrid cell renderer component despite using observables Here are the methods I've attempted so far: Directly calling the service within the cellRenderer component Invoking the service in the ...

Lack of intellisense support for .ts files in Visual Studio Code

Currently, I am using Visual Studio Code 1.17.2 on Arch Linux to kickstart my work with Node.js/Angular4. To avoid confusion caused by loosely typed code, I have decided to switch to TypeScript for my NodeJS server as well. This is why my main file is name ...

When Typescript calls the toString method on a Function, it produces unexpected characters like "path_1, (0, promises.writeFile)"

I'm currently attempting to convert a function into a string for transmission to a worker thread for execution. However, when imported code is included, the resulting string contains strange characters. import { HttpStatus } from '@nestjs/common& ...

When the page is refreshed, Vercel's Next.JS success/error pattern is thrown due to the "window is not defined" error

Currently, I am working on enhancing a Next.js website that is hosted on Vercel. Upon deploying the page, I encountered the following error initially: GET] / 17:53:00:19 2022-09-12T14:53:00.262Z 938c1a2e-ce7c-4f31-8ad6-2177814cb023 ERROR Uncau ...

What is the significance of registering subcomponents in Angular through NgModule? How does this relate to the concept of encapsulation

Having experience with various frameworks and architectural principles, I find it puzzling that the Angular Team chose to deprecate the directivies property of a Component in RC6 in favor of declarations in NgModule. Typically, architecture emphasizes enc ...