Utilizing a public function in an extended HttpClass

In order to dynamically apply headers and URL paths, I have created an extended HttpClass. Here is what it looks like:

custom-http.ts

export enum Type {
  PREAUTH = 0,
  AUTH = 1,
  PRINTER = 2,
  TERMINAL = 3
}

@Injectable()
export class CustomHttp extends Http {
  private typesOn: Array<any> = [false, false, false, false];

constructor(backend: ConnectionBackend, defaultOptions: RequestOptions) {
    super(backend, defaultOptions);
    this.presetPetition(Type.AUTH);
}

presetPetition(type: number) {
    this.typesOn.forEach(t => (t = false));
    this.typesOn[type] = true;
}

request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
    return super.request(url, options);
}

get(url: string, options?: RequestOptionsArgs): Observable<Response> {
    return super.get(this.updateUrl(url), this.getRequestOptionArgs(options));
}

private updateUrl(req: string) {
  if (this.typesOn[Type.AUTH]) {
    return environment.apiURL + req
  } else {
    return req
  }
}

app.module.ts

providers: [
 CustomHttp,
  {
    provide: Http,
    useFactory: httpFactory,
    deps: [XHRBackend, RequestOptions]
  }
]

http.factory.ts

export function httpFactory(xhrBackend: XHRBackend, requestOptions: 
RequestOptions): Http {
  return new CustomHttp(xhrBackend, requestOptions);
}

When trying to change the type of HTTP request, I import CustomHttp into the component/service and call presetPetition() just before making the HTTP request.

An error message saying "No Provider for Backend Connection" is shown. I realize that redundant provider imports may be causing this issue (Http and AppHttp).

How can I access a public function in an extended class? Am I approaching this problem incorrectly?

Answer №1

The coding standard of Angular is being violated here. It is recommended to create an API service specifically for URL setting and CRUD operations, and extend the HTTP service of Angular for authentication purposes.

For a common API setup:

import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions } from '@angular/http';

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';

@Injectable()
export class BaseService {

  private headers = new Headers({ 'Content-Type': 'application/json', 'charset': 'UTF-8' });
  private options = new RequestOptions({ headers: this.headers });

  constructor(private http: Http) { }

  // Get all
  getAll(url: any): Observable<any> {
    return this.http.get(url).map(res => res.json());
  }

  // Count all
  count(url: any): Observable<any> {
    return this.http.get(url).map(res => res.json());
  }

  // add
  add(url: any, entity: any): Observable<any> {
    return this.http.post(url, JSON.stringify(entity), this.options);
  }

  // Get by id
  getById(url: any, entity: any): Observable<any> {
    return this.http.get(url + `/${entity._id}`).map(res => res.json());
  }

  // Update by id
  editById(url: any, entity: any): Observable<any> {
    return this.http.put(url + `/${entity._id}`, JSON.stringify(entity), this.options);
  }

  // Delete by id
  deleteById(url: any, entity: any): Observable<any> {
    return this.http.delete(url + `/${entity._id}`, this.options);
  }

}

Link to Base Service GitHub repo

For extending the HTTP service, refer to:

Extending HTTP Provider in Angular

This approach can be beneficial for your project.

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 HTTPS protocol seems to be causing CORS issues, but I can access http://localhost without

In my current project using TypeScript with Express, I encountered an issue with implementing CORS. In the past, I have successfully added CORS to regular Express.js projects without TypeScript and assumed it would work similarly. However, when making a ba ...

Encountering an issue while creating an Ionic v6 Cordova Android Angular13 application, the error message "Project target does not exist" is displayed, indicating an unhandled exception

I am currently in the process of developing an ionic v6 app using the latest versions of cordova and angular13. However, I have encountered an error when running ionic cordova build android https://i.sstatic.net/i8QFO.png For more information on reproduc ...

Navigating the color scheme in Angular Material theme to identify the specific colors utilized for the components

Our project utilizes angular-material from the official website, where we can set up custom color themes by following this guide: Theming Guide. We have a designer on board who wants to create a UI Kit with specific colors, such as different input states. ...

Winston logs are unable to function within the Docker Container

I'm currently working on developing a nodejs/express app with typescript and have recently installed the winston package using npm install winston. I came across this helpful article that I've been following closely. Now, my goal is to dockerize ...

Preventing redundant function calls in Angular's keyup event

My objective is to: Fetch data by calling a service and binding it on the ngOnit() lifecycle hook. Implement a functionality where, in a text input field, an API call is triggered only after a user stops typing for a second (debouncing between user keystr ...

Guide to creating a SVG component using typescript in a React application

I have a component where I am passing SVG icons props as an array containing my SVG component data. However, TypeScript is showing me an error while working with Material UI. Type '{ key: number; data: { id: number; icon: ReactNode; }; }' is not ...

Assigning string properties to different types

I have numerous data types, each with a common property called dataType, and I am currently mapping each one to that specific value: interface GroupData { dataType: "group"; name: string; people: PersonData[]; } interface PersonData ...

Is it possible to implement a cast operator in Typescript?

After using JSWEET to transpile a large Java project, I noticed that it changed types such as Enumeration<Object> directly to Enumeration<any> in TypeScript. Previously in the Java environment, it was possible to assign an array Object[] to an ...

Angular 2 cleaning up subscriptions when view is destroyed

I've developed an interesting "appService" that serves as the intermediary between all my components, handling interactions like forms and navigations. This service boasts multiple event emitters to which various components subscribe for different pu ...

Unable to send a function as props to a child component in TypeScript

Within my application, I have a parent component that holds a state and a setState function. This state and function are then passed down to a child component in order to retrieve values (such as input field data). When the function is triggered in the chi ...

Encountering a type error when using types/d3-array

There was an ERROR in the TypeScript file: node_modules/@types/d3-array/index.d.ts on line 36. The error states: "error TS2574: A rest element type must be an array type." The code causing the issue is as follows: export type NestedInternMap<TObject, T ...

Simultaneously leveraging angular and node

Currently, I'm developing a basic Angular application and so far everything on the Angular side is functioning properly. In order to incorporate Express into my project, I created a file called server.js. However, when attempting to run node server.j ...

The global declaration of Typescript is only accessible within the node_modules/@types directory

Scenario As I develop an npm package using Typescript, I include types that are shipped alongside the library in the following structure: my-package |- index.js |- index.d.ts |- package.json The index.d.ts file includes global declarations like: declare ...

Extension method Observable<T> in Angular6 typescript is a powerful feature that allows

I've been attempting to create an extension method for Observable import { Observable } from 'rxjs/Observable'; declare module 'rxjs/Observable' { interface Observable<T> { customFilter<T>(this: Observable<T& ...

Using TypeScript: Functions incorporating properties

Recently, I made an interesting discovery in JavaScript: function foo() { console.log("FOO"); } foo.bar = "FOOBAR"; foo(); // logs "FOO" console.log(foo.bar); // "FOOBAR" This got me thinking: How would I repres ...

Vue 3 Single Page Application. When selecting, it emits the language and the contentStore does not update the content exclusively on mobile devices

My Vue 3 Single Page Application is built on Vite 4.2 and TypeScript 5.02. When I click to select a language, it emits lang.value and in the parent component App.vue, contentStore should update the content. It works flawlessly on my Linux Ubuntu desktop i ...

What could be the reason for the Angular dropdown values not appearing?

Encountering an issue with binding data to a dropdown element, as the dropdown displays NOTHING SELECTED. <select #classProductTypeCombobox name="classProductTypeCombobox" class="form-control col-md-3" [(ngModel)]="classifica ...

Angular validation is malfunctioning for fields that have names ending with periods

Currently in the process of generating dynamic input fields <input class="form-control-lg form-control" placeholder="{{data.DisplayName}}" formControlName="{{data.labelName}}" type="text" maxlength="13" ...

Combining Angular and Material Design: matdrawer and mattoolbar creating an overlapping effect

I'm currently facing a challenge in trying to construct a drawer that includes a mattoolbar, intended to overlap the primary toolbar of my application. Despite my efforts, I have been unable to rearrange the drawer higher up in the component hierarch ...

What is preventing me from including an additional parameter in a function in TypeScript?

I am currently developing a task management application. I am facing an issue while attempting to incorporate the event and items.id into a button function for actions like delete, edit, or mark as completed. While this functionality works smoothly in pla ...