Leveraging imported libraries from a parent class is a common practice in Angular

"angular2": "2.0.0-beta.17",

How can I import { Http, Response } from 'angular2/http'; in my Base class and use http in the child classes?

Is there a way to achieve this?

P.S. I'm open to hacks, workarounds, and unconventional solutions.

The base class:

import { Http, Response } from 'angular2/http';

export class ServiceBase {
  constructor (private http: Http) {}

}

And a child class:

import { ApiServiceBase } from '../../api-service-base';
import { Injectable }     from 'angular2/core';
// import { Http, Response } from 'angular2/http';
import { AuthUser }       from './auth_user';
import { Observable }     from 'rxjs/Observable';
import { Headers, RequestOptions } from 'angular2/http';
import 'rxjs/add/operator/toPromise';

@Injectable()
export class LoginService extends ApiServiceBase {
  constructor () {
    super();
  }
  private url = 'http://localhost:8080/api/signin';

  login (user: AuthUser): Promise<AuthUser> {
    let body = JSON.stringify(user);
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });
    return this.http.post(this.url, body, options)
               .toPromise()
               .then(this.extractData)
               .catch(this.handleError);
  }

  private extractData(res: Response) {
    console.log(res);
    if (res.status < 200 || res.status >= 300) {
      throw new Error('Bad response status: ' + res.status);
    }
    let body = res.json();
    return body.data || { };
  }

  private handleError (error: any) {
  }
}

Answer №1

Angular2 does not support using a parent class to define dependency injection of sub classes.

If you need to use the http instance in the parent class, one way to work around this limitation is by creating a custom decorator to handle dependency injection metadata:

export function CustomInjectable(annotation: any) {
  return function (target: Function) {
    var parentTarget = Object.getPrototypeOf(target.prototype).constructor;
    var parentAnnotations = Reflect.getMetadata('design:paramtypes', parentTarget);

    Reflect.defineMetadata('design:paramtypes', parentAnnotations, target);
  }
}

This approach allows the child class to inherit metadata from the parent constructor rather than its own. Here's an example of how you can implement it:

@Injectable()
export class BaseService {
  constructor(protected http:Http) {
  }
}

@CustomInjectable()
export class TestService extends BaseService {
  constructor() {
    super(arguments);
  }

  test() {
    console.log('http = '+this.http);
  }
}

You can view a working example on Plunker here: https://plnkr.co/edit/DIMyUB6rCE5d78dPlPZB?p=preview.

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

Tips for restricting User access and displaying specific sections of the menu

I have a component that utilizes map to display all menu parts. Is there a way to make certain parts of the menu hidden if the user's access rights are equal to 0? const Aside: React.FunctionComponent = () => { const[hasRight, setHasRight] = us ...

Can TypeScript support promise chaining in a functional way?

It appears that in the realm of JavaScript, one has the capability to execute: function extendPromise(promise) { return promise.then(new Promise(() => {})); } However, when incorporating types into the mix, such as function extendTypeScriptPromis ...

What are the specific HttpRequest and HttpEvent types utilized within an Angular interceptor?

I have recently started working with Angular and I am currently implementing an interceptor in my Angular project. In the code snippet below, the types for HttpRequest and HttpEvent are specified as any. However, I would like to specify the proper type f ...

Child routes cannot be included when ..., so make sure to specify "..." in the parent route path

I've been working on setting up child routing within my project, and here is the current folder structure I have: app |--home/ | |--home.component.ts |--login/ | |--login.ts |--appShell/ | |--app.component.ts |--apps/ |- ...

What is the purpose of specifying an 'any' return type in TypeScript?

As an example: function retrieveUserInformation(input: any): any { return input } It may seem unnecessary to declare that "any data type can be returned". Is there a specific reason for this? ...

Angular's input event fails to trigger for dynamically generated fields when pasted into them

When working with a form that has dynamically generated input fields, I encountered an issue. I needed to display a preview of the input contents on a div while pasting content into the fields. This project is built using Angular 11. Below is my .ts file: ...

Angular app experiencing pre-flight authentication error while Postman/Rest Client functions properly

Seeking assistance on fetching data from an Angular 5 application using an https endpoint. The process involves adding an Authentication token to the HttpHeaders and utilizing the HttpClient component for sending a get request. const headers = new Http ...

Issue with displaying React component markup on "Show code" in Storybook versions 7 and 8

I have been searching for a solution for a while now, exploring various sources such as similar posts, Storybook documentation, and GitHub discussions, but I haven't found a resolution yet. After upgrading to v7 and then v8, the "Show code" tab on the ...

When the local server and SPA are running on different ports, utilizing an authentication cookie can help bridge the

I currently have a nest.js webserver running on localhost:3000, with an angular frontend served to localhost:4200 (using the dev server). These ports are set as defaults. My authentication process involves sending an access-token in a cookie to the front ...

The variable 'module' is required to be of type 'any', but it is currently identified as type 'NodeModule'

I am currently working on a project using Angular and have just installed version 1.0.5 of ng2-dropdown-treeview. After installation, I restarted my server by running npm start. Upon checking the server log, I encountered the following error message: [PA ...

Stop images from constantly refreshing upon each change of state - React

Within my component, I have incorporated an image in the following way: <div className="margin-10 flex-row-center"> <span> <img src={spinner} className="spinner" /> ...

Struggling with intricate generic type mapping of records in Typescript

Whew...spent an entire day on this. My brain is fried... I am developing a type-safe mapper function that determines which props are needed based on the mapping type and can predict the output types based on the ReturnType. However, it seems like each re ...

Experiencing a console error which reads: "SyntaxError: Missing ) after argument list."

While working on configuring a new React CSR app and incorporating some boilerplate libraries, I encountered an error in the console: Uncaught SyntaxError: missing ) after argument list (at @emotion_react_macro.js?v=30f6ea37:29894:134) I am hesitant to ma ...

What is the best practice for Angular: running production build before or after testing?

When developing a Java application for production, I typically set up the build process to create the production artifacts first and then run tests against those artifacts. Recently, I joined an Angular project and noticed that the build process is struct ...

What is the best method for retrieving GET parameters in an Angular2 application?

Is there a way in Angular2 to retrieve GET parameters and store them locally similar to how sessions are handled in PHP? GET Params URL I need to obtain the access_token before navigating to the Dashboard component, which makes secure REST Webservice cal ...

Printing from a lengthy React DOM using window.print only generates a single page

My React component is capable of rendering markdown and can span multiple pages. Everything looks great when the component is displayed in the browser - scrolling works perfectly. However, whenever I try to print the page using window.print or ctrl + P, ...

The onNodeContextMenuSelect function does not seem to be functioning properly within the p-tree

<p-tree [value]="files" selectionMode="single" (onNodeContextMenuSelect)="showContect($event)" > </p-tree> Whenever I right click, the event doesn't seem to be triggering. Instead, the default browser c ...

Ensuring TypeScript's strict null check on a field within an object that is part of an

When using TypeScript and checking for null on a nullable field inside an object array (where strictNullCheck is set to true), the compiler may still raise an error saying that 'Object is possibly undefined'. Here's an example: interface IA ...

The JSX component cannot use 'Router' as a valid element

Error Message The error message states that 'Router' cannot be used as a JSX component because its return type 'void' is not a valid JSX element. TS2786 import App from './App'; 5 | > 6 | ReactDOM.render(<Router ...

The sequence of events in React Native following a navigation.navigate call

Seeking suggestions and advice, I currently have the following 2 lines of code within a react native expo component: this.props.navigation.navigate("App"); patchUser(this.state.dataSource.userInfo.username, this.state.dataSource.userInfo.firstN ...