Expanding on the http class to utilize custom properties within Angular2 typescript

I have developed a CustomHttp class that extends Http similar to the example provided here:

To integrate this CustomHttp class, I included providers in the bootstrap function as shown below:

bootstrap([
    HTTP_PROVIDERS,
    { provide:Http,
        useFactory: (backend: XHRBackend, defaultOptions: RequestOptions, errorNotifier: NotificationHandlerService, 
                     authService: AuthInfoService) => {
            return new CustomHttp(backend, defaultOptions, errorNotifier, authService);
        },
        deps: [ XHRBackend, RequestOptions, NotificationHandlerService,  AuthInfoService]
    },
  ])

All overridden methods like get and post are fully functional. However, when I added a custom property and method to the CustomHttp class, I encountered an issue trying to access it from outside the CustomHttp:

@Injectable()
export class CustomHttp extends Http {

...
private myCustomProperty = 'It's custom';

public getCustomProperty() {
    return this.myCustomProperty;
}
...

}

=====================

import {Http} from '@angular/http';

export class MainComponent {

    constructor(private _http: Http) {
       this._http.getCustomProperty(); // this method doesn't exist in Http
    }
}

Can anyone suggest how to access custom methods and properties of CustomHttp?

Answer №1

To implement this functionality, you can attempt the following approach which involves type casting from Http to CustomHttp:

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { CustomHttp } from './custom.http';

@Injectable()
export class BooksService {

  constructor(private http:Http) {
    console.log((<CustomHttp>this.http).someProperty);
  }

  (...)
}

Utilize the CustomHttp class shown below:

@Injectable()
export class CustomHttp extends Http {
  someProperty:string = 'some string';

  (...)
}

Answer №2

import {HttpClient} from '@angular/common/http';
import {CustomService} from '/another/path';

export class DisplayComponent {

    constructor(private _httpClient: CustomService) {
       this._httpClient.getCustomData(); 
    }
}

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 7: Show selected value upon clicking Radio button

I am having an issue with a radio button where I need to display a value when it is clicked. For example, when the "weekly" option is selected, I want it to display "Weekly" in the "Selection" element. I have tried to implement this but it is not working a ...

Counting up in Angular from a starting number of seconds on a timer

Is there a way to create a countup timer in Angular starting from a specific number of seconds? Also, I would like the format to be displayed as hh:mm:ss if possible. I attempted to accomplish this by utilizing the getAlarmDuration function within the tem ...

Angular2 material select component is malfunctioning

Currently incorporating Google material 2 into my Angular 2 project and utilizing either Reactive Form or Data Driven form. states = [ { value: 'KA', viewValue: 'Karnataka' }, { value: 'GJ', viewValue: 'Gujarat&a ...

`"Type is invalid" error occurring with component after importing it into a different project``

I am currently working on developing a custom Storybook 7 Typescript component library with React. I have successfully imported this library into another project using a private NPM package. However, one of the components in the library, specifically the ...

Utilizing a Custom Validator to Compare Two Values in a Dynamic FormArray in Angular 7

Within the "additionalForm" group, there is a formArray named "validations" that dynamically binds values to the validtionsField array. The validtionsField array contains three objects with two values that need to be compared: Min-length and Max-Length. F ...

What is the best way to hide certain buttons from specific users in Angular using the If condition?

I am facing an issue with my array of blocked_users, where I need to hide certain buttons if a user is in the blocked_users list. Below is the code snippet from my angualr.component.html: <div *ngIf="!(userId in event.blocked_users)"> ...

Disabling an anchor using the 'disabled' property is proving to be a challenge for me

I'm attempting to dynamically enable or disable an anchor element based on the user's role. So far, I've tried a few different methods: document.getElementById('myBtn').disabled = true; However, this returns an error: The propert ...

Angular 2: Streamlining user interface connections with extensive data rows

My challenge lies in displaying a list of items stored in an array[] when the user clicks on a tab. The data set contains around 10k rows, which is quite large, and currently takes approximately 2 to 3 seconds to render on the UI after the click event. I a ...

Exploring the Angular 4 Cronstrue Idea: Transforming cron syntax into readable strings[From CronJobs to Cronstrue]

Can anyone provide an example of using the cronstrue concept to convert cron expressions into human-readable strings within Angular 4? I am looking for a library or plugin in Angular 4 that can convert cronjob schedule expressions into readable text [cron ...

Utilizing props in styled-components: A beginner's guide

I am trying to pass a URL to a component so that I can use it as the background image of the component. Additionally, I need to check if the URL is empty. Component: <BannerImg/> CSS (styled): `const BannerImg = styled.img` background-image: url( ...

Is there a way to prevent IntelliJ from creating .js files when working with .ts source code?

Working on a mixed Java/Typescript project with Maven as the build tool, I utilize the frontend-maven-plugin to successfully build from the command line. However, I am encountering an issue with IntelliJ 2018.2 where it keeps transpiling .js files for my . ...

Navigating conflicts between packages that utilize TypeScript can be tricky. Here are some strategies for handling these situations

I recently encountered an issue while following a tutorial to create a WhatsApp clone using Meteor. The tutorial link is here The problem arose at the end of section 8 when I executed the $meteor reset command as directed. However, upon running the $ n ...

Issue: The formGroup function requires a valid FormGroup instance to be passed in. Data retrieval unsuccessful

My goal is to retrieve user data from a user method service in order to enable users to update their personal information, but I'm encountering an error. Currently, I can only access the "prenom" field, even though all the data is available as seen in ...

Creating custom disabled button styles using TailwindUI in a NextJS application

I had a NextJS application that utilized Atomic CSS and featured a button which becomes disabled if a form is left unfilled: <Button className="primary" onClick={handleCreateCommunity} disabled={!phone || !communi ...

Experiencing a typeerror with the Event attribute

I encountered an issue while trying to target an event. Here is what I attempted: public gotoPage(event: Event): void { const gettest = (event.target as HTMLElement)?.getAttribute('href'); if (href) { const testModule = "valu ...

Instead of tapping the enter key, try searching by keying up

I am implementing a search pipe in Angular for filtering data based on user input import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'searchPipe', pure: false }) export class SearchPipe implements PipeTransform { ...

Setting multiple dynamic values for select inputs in reactive forms can be achieved by following these steps

I am currently developing a dynamic select feature using reactive form in my project. So far, I have successfully implemented dynamic selects with the same values. However, I now have a requirement to load the dropdown values dynamically based on certain c ...

I am facing an issue with my interface - the variable designed to store boolean values

Something unusual happened with Typescript - I assigned a string value to a boolean variable, but no error was generated. I purposely triggered an error in order to observe how Typescript would react, only to find that it did not produce the expected erro ...

What could be causing the Properties Array to come back as undefined?

When attempting to add an item to an array stored in the properties, I am encountering an error: "Cannot read properties of undefined (reading 'value')." Within the props, the following interfaces are defined: ILinkItemProps.ts export interface ...

What is the best way to apply DateRange filtering in a Kendo Ui Grid?

Currently I am working with the Kendo Ui Grid and attempting to implement filtering by DateRange. Here is a snippet of my current code: HTML: <kendo-grid-column field="createdate" title="Creation Date" width="150"> <ng-template kendoGridFilterC ...