Error in Angular6: Why can't handleError read injected services?

It appears that I am facing an issue where I cannot access a service injected inside the handleError function.

constructor(private http: HttpClient, public _translate: TranslateService) { }        
login(user: User): Observable<User> {               
      console.log( this._translate); // The service is accessible here    
      return this.http.post<User>("http://...../login",  params, httpOptions)
            .pipe(catchError(this.handleError));                  
}

private handleError(error: HttpErrorResponse) {    
      console.log( this._translate); // However, the service is not accessible here                           
      return throwError(error.error);                     
};

Answer №1

When passing an unbound function as an argument in

.pipe(catchError(this.handleError));
, you are losing the context.

It is recommended to either use:

  .pipe(catchError(this.handleError.bind(this)));

or utilize an arrow function:

       .pipe(catchError((err) => this.handleError(err)));    

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

The value of an Angular array seems to be disappearing after being copied to another array and then cleared

I have encountered an issue while working with arrays. I am initializing two arrays - one with some values and another as empty. However, when I assign the items from the first array to the second array and then clear the first array, it unexpectedly clear ...

The error message "InvalidPipeArgument: '[object Object]' for pipe 'AsyncPipe' in Angular 6 and Firebase" indicates a problem with the data being passed to the AsyncPipe in

**Error: InvalidPipeArgument: '[object Object]' for pipe 'AsyncPipe'. ** I am encountering a problem with unsubscribing from the observable. My Angular-cli version is 6.0.3 This is the HTML code in home.component.html <div class ...

Importing configuration file in CRA Typescript with values for post-deployment modifications

I am currently working on a React app that utilizes Create React App and Typescript. My goal is to read in configuration values, such as API URLs. I have a config.json file containing this data, here's a sample snippet with placeholder information: { ...

What sets apart TypeScript's indexed types from function signatures?

I am curious about the distinction between indexed type and function signatures in TypeScript. type A = { _(num: number): void; }['_']; type B = { _(ten: 10): void; }['_']; let a: A = (num) => { console.log(num); }; let b: B ...

What is the method for creating pipes that filter multiple columns?

My pipe is designed to work exclusively for the "name" column and not for the author anymore. transform(items: Book[], filter: Book): any { if (!items || !filter) { return items; } // Filter items array; keep items that match and retu ...

Is it possible to exclude a certain prop from a styled component that has emotions?

Within my code, there exists a component called BoxWithAs, which is defined as follows: const BoxWithAs = styled.div( { WebkitFontSmoothing: 'antialiased', MozOsxFontSmoothing: 'grayscale' // And more … } ); Everythin ...

What is the process for specifying a data type for a pre-existing npm package module?

I am currently working on converting a codebase that utilizes nodemailer along with the nodemailer-html-to-text plugin to TypeScript. While nodemailer has @types definitions available, the same is not true for nodemailer-html-to-text. How can I go about ...

The content security policy is preventing a connection to the signalr hub

Currently, I am developing an application using electron that incorporates React and Typescript. One of the features I am integrating is a SignalR hub for chat functionality. However, when attempting to connect to my SignalR server, I encounter the followi ...

Link a YAML file with interfaces in JavaScript

I'm currently learning JavaScript and need to convert a YAML file to an Interface in JavaScript. Here is an example of the YAML file: - provider_name: SEA-AD consortiumn_name: SEA-AD defaults: thumbnail Donors: - id: "https://portal.brain ...

The issue with converting a string into an object in Typescript

I am having trouble converting the JSON response from the websocket server to a TypeScript object. I've been trying to debug it but can't seem to find where the error lies. Can anyone assist me in resolving this issue? Below is the code snippet ...

Encountered a TypeScript error: Attempted to access property 'REPOSITORY' of an undefined variable

As I delve into TypeScript, a realm unfamiliar yet not entirely foreign due to my background in OO Design, confusion descends upon me like a veil. Within the confines of file application.ts, a code structure unfolds: class APPLICATION { constructor( ...

"Exploring the depths of Webpack's module

This is my first venture into creating an Angular 2 application within MVC Core, utilizing TypeScript 2.2, Angular2, and Webpack. I have been closely following the Angular Documentation, but despite referencing the latest NPM Modules, I encounter errors w ...

Angular 2 is throwing an error: Unhandled Promise rejection because it cannot find a provider for AuthService. This error is occurring

My application utilizes an AuthService and an AuthGuard to manage user authentication and route guarding. The AuthService is used in both the AuthGuard and a LoginComponent, while the AuthGuard guards routes using CanActivate. However, upon running the app ...

Unable to resolve the Typescript module within a different file

I am in the process of transitioning my React app to TypeScript. Currently, everything is working fine. However, I encountered an issue after adding the TypeScript compiler and renaming files to .ts and .tsx extensions - it is now throwing a "module not fo ...

Developing Angular components with nested routes and navigation menu

I have a unique application structure with different modules: /app /core /admin /authentication /wst The admin module is quite complex, featuring a sidebar, while the authentication module is simple with just a login screen. I want to dyn ...

React-Redux: Unable to access the 'closed' property as it is undefined

Encountered a problem when using dispatch() in React-Redux. Specifically, the action below: export const fetchMetrics = () => { dispatch(fetchMetricsBegin); APIService.get('/dashboard/info/') .then((response) => { ...

Nextjs build: The specified property is not found in the type 'PrismaClient'

I have a NextJS app (TypeScript) using Prisma on Netlify. Recently, I introduced a new model named Trade in the Prisma schema file: generator client { provider = "prisma-client-js" } datasource db { provider = "postgresql" url ...

How can I modify the appearance of folders in FileSystemProvider?

I have created an extension for vscode that includes a virtual filesystem with fake directories and files. While the extension is functioning properly, I am facing some challenges in customizing certain aspects due to lack of documentation. 1) I need to u ...

Can TypeScript and JavaScript be integrated into a single React application?

I recently developed an app using JS react, and now I have a TSX file that I want to incorporate into my project. How should I proceed? Can I import the TSX file and interact with it within a JSX file, or do I need to convert my entire app to TSX for eve ...

The FaceBook SDK in React Native is providing an incorrect signature when trying to retrieve a token for iOS

After successfully implementing the latest Facebook SDK react-native-fbsdk-next for Android, I am facing issues with its functionality on IOS. I have managed to obtain a token, but when attempting to use it to fetch pages, I keep getting a "wrong signature ...