When you extend the BaseRequestOptions, the injected dependency becomes unspecified

Implementing a custom feature, I have chosen to extend BaseRequestOptions in Angular2 to incorporate headers for every request. Additionally, I have introduced a Config class that offers key/value pairs specific to the domain, which must be injected into my derived class:

import { BaseRequestOptions } from '@angular/http';
import { Config } from '../../config/configuration';

export class DefaultRequestOptions extends BaseRequestOptions {
  constructor(private config: Config) {
    super();

    Object.keys(this.config.api.headers).map((key) => {
      this.headers.append(key, this.config.api.headers[key]);
    });
  }
}

Within my module setup, the provider is defined as follows:

@NgModule({
  . . .,
  providers: [
    . . .,
    { provide: RequestOptions, useClass: DefaultRequestOptions }
  ]
})
. . .

An issue arises where this.config is being identified as undefined inside DefaultRequestOptions. Despite having used the Config class successfully as an injected dependency in other areas, setting values manually for this.headers solves the problem.

What could be causing the configuration to be undefined within DefaultRequestOptions?

Answer №1

Provider classes in Angular do not always require the @Injectable() decorator, unless they have constructor parameters that need to be injected. If your class requires injections, it is recommended to use the @Injectable() decorator on your providers at all times. This helps prevent issues where the decorator is forgotten when required.

@Injectable()
export class DefaultRequestOptions extends BaseRequestOptions {

Upon testing

Even after adding the decorator, the issue persists. The problem arises from extending a class, like BaseRequestOptions, that already uses @Injectable(). In this scenario, the parent class' constructor is called instead of the child class'. To resolve this, consider extending RequestOptions instead, as it does not have the @Injectable() decorator.

@Injectable()
class DefaultRequestOptions extends RequestOptions {
  constructor(public config: Config) {
    super({method: RequestMethod.Get, headers: new Headers()})

    this.headers.append('data', this.config.data);
  }
}

Note the usage of super(). This mimics what BaseRequestOptions does.

If you prefer sticking with the current setup using BaseRequestOptions, you can utilize a factory method instead of relying on Angular's automatic creation:

{
  provide: RequestOptions,
  deps: [ Config ],
  useFactory: (config: Config) => {
    return new DefaultRequestOptions(config);
  }
}

Answer №2

Forget peeskillet's complicated method, here's a simpler way to do it. When setting up your provider, make sure to include the necessary dependencies like this:

providers: [
{
    provide: RequestOptions,
    useClass: DefaultRequestOptions,
    deps: [Config]
};

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

Encountered an unexpected interpolation ({{}}) in column 3 of Data Bind RouterLink (Angular 2) that was expecting an expression

Encountering difficulties passing data to my routerLink. The goal is to change the route when the id reaches 4 within the ngFor loop. <input type="button" class="btn-cards" [ngClass]="getStyle(negociacao)" [routerLink]="['/{{negociacao.rota}}&apo ...

The Angular 2 HTTP GET method is throwing a type 3 error when trying to access the

i am encountering an issue while trying to retrieve a response from my asp.core api within Angular 2. The error message received is: "Object { _body: error, status: 0, ok: false, statusText: "", headers: {…}, type: 3, url: null }" Component: import { C ...

Get the date string formatted for an Angular2 date range picker

In my Angular2/Spring web application, I am utilizing a calendar from the following sources: https://www.npmjs.com/package/ng2-daterangepicker http : // www. daterangepicker . com/ The issue I am encountering is with formatting the date output. Accordin ...

Problem: Unable to open Angular href links on IOS devices

I am experiencing an issue with a shared-code application in Android and IOS. The link successfully opens on an Android device but fails to open on an IOS device. Are there any differences between the two platforms that could be causing this discrepancy? ...

What could be the reason for the exclusion of 'null' from the return type of Document.getElementById in VS Code?

Versions of VS Code: Experimenting with 'Type Narrowing' Code in VS Code has brought to my attention a discrepancy between the information provided by VS Code and TypeScript Playground: In VS Code, it shows that the return type of Document.getE ...

The user authentication service indicates that no user is currently logged in

Currently, I am working on implementing a route guard to distinguish between authenticated users and guests. In order to achieve this, I have created an auth-guard service along with an auth service. Although the user data is successfully stored in the loc ...

Developing an npm package for storing a communal instance

I am interested in developing an npm library that can be initialized with a specific set of keys and then utilized throughout an entire project. Here is an illustration of how I envision its usage: In the main component or page import customLib from &quo ...

The 'ObjectID' property is not present in the 'CollectionStatic' data type

Encountering an issue with the MongoDB npm module: mongoId = new Mongo.Collection.ObjectID()._str; Attached is a screenshot for reference. Appreciate any assistance.https://i.sstatic.net/EHdMo.png ...

Exploring the power of Next.js, Styled-components, and leveraging Yandex Metrica Session Replay

I'm currently involved in a project that utilizes Next.js and styled-components. In my [slug].tsx file: export default function ProductDetails({ product }: IProductDetailsProps) { const router = useRouter(); if (router.isFallback) { return ( ...

Creating a secure API that is accessible exclusively by the front-end: A step-by-step guide

I've been scouring the internet for a while now, trying to understand the concept of creating a private API exclusively between the front-end and back-end. What I really want is an API that can only be accessed through the front-end interface, not via ...

Tips for preventing the impact of angular mat-panel position changes on matdialog

In my Angular project, I utilized Matmenu and MatDialogModule. I needed to change the position of mat-menu, so I achieved this by adding the following snippet to my .scss file. ::ng-deep .cdk-overlay-pane { transform: translate(78%, 10%); } However, ...

`In Vue.js, it is not possible to access a data property within a

I encountered an issue while attempting to utilize a property of my data within a computed method in the following manner: data() { return { ToDoItems: [ { id: uniqueId("todo-"), label: "Learn Vue", done: false }, ...

In Angular, a white screen may suddenly appear if the scrolling speed is too fast

My experience has been primarily on Chrome. I've noticed that when I scroll for a long time, the data on the screen disappears briefly and then reappears after a few seconds. Is there a resolution for this problem? Thank you, ...

Encountering an error on Ionic 4, Angular 8: Unable to access property 'subscribe' of undefined

I have a project that utilizes Ionic 4 and Angular 8. The project requires integration with a payment gateway service, which I am accomplishing using the Ionic 4 InAppBrowser plugin to open the payment gateway site. This is how I've implemented it: ...

The type '{}' does not contain a property named 'map'

Recently delving into TypeScript, and I'm curious about the process of typing an axios response when storing it in a state variable. I've initiated a basic API call from App.tsx, which returns the following object: {data: {…}, status: 200, s ...

Using RxJS iif with various conditions in combination with Angular 9

I am currently working on creating a service using Angular that will retrieve a specific data set. The format of the object returned by the API looks like this: { status: string, totalResults: number, results: [array of objects] } My goal is to ret ...

A step-by-step guide on leveraging swagger-autogen in TypeScript applications

Is it possible to integrate the swagger-autogen module into a Typescript project? I have attempted multiple methods, but have been unsuccessful. The error message "Failed" keeps appearing when using a swagger.js file: const swaggerAutogen = require("swagge ...

Utilize JSX attributes across various HTML elements

I'm looking for a solution to efficiently add JSX attributes to multiple elements. Here are the example attributes I want to include: class?: string; id?: string; style?: string; And here are the example elements: namespace JSX { interface Int ...

Generate an alert with a numerical input field - Ionic

How can I create an input with type number in AlertController? I attempted to implement this, but the input only accepts text and not numbers. const alert = this.alertCtrl.create({ title: 'Add Ingredient', inputs: [ { name: ' ...

Creating an HTTP gateway with Observables

When dealing with multiple requests, I need to pause them until the authentication of the http request has been confirmed. Essentially, I require an http gate where some requests can pass without authentication, while others need to wait for the token to b ...