Angular 6: Exploring the Challenges of Extending Services Without Sacrificing the Functionality of ChildService

As I was developing multiple angular REST-services for my frontend, I came up with the idea of creating a base class BaseRestService to handle common functionalities like headers and helper functions.

However, I encountered TypeErrors when trying to call certain functions in my child service that extends the BaseRestService. Upon debugging, I noticed that the child service was being treated as an instance of BaseRestService instead of SomeExampleChildSerivce. Can anyone shed light on this behavior or point out where I might be going wrong?

Below is the code for my BaseRestService and a sample ChildService:

BaseRestService:

@Injectable({
  providedIn: 'root'
})
export abstract class BaseRestService {
  headers = new HttpHeaders({
    'Content-Type': 'application/json',
    'Authorization': `JWT ${this.authService.getToken()}`
  });

  constructor(
    public httpClient: HttpClient,
    public logger: LoggingService,
    public authService: AuthenticationService,
  ) { }

  public refreshToken(): void {
    this.headers = new HttpHeaders({
      'Content-Type': 'application/json',
      'Authorization': `${this.authService.getToken()}`
    });
  }
}

ChildService:

@Injectable({
  providedIn: 'root'
})
export class DimensionService extends BaseRestService{
  private url: string = `${BASE_URL}/dimensions`;

  constructor(
    public httpClient: HttpClient,
    public logger: LoggingService,
    public authService: AuthenticationService,
  ){
    super(httpClient, logger, authService);
  }

  get(url: string): Observable<DimensionAttribute> {
    return this.httpClient.get<DimensionAttribute>(url, { headers: this.headers })
  }

  list(url?: string, page = 0, size = 20): Observable<Page<DimensionAttributeWrapper>> {
    if (!url) url = `${this.url}?page=${page}&size=${size}`;
    return this.httpClient.get<Page<DimensionAttributeWrapper>>(url, { headers: this.headers })
  }
}

Answer №1

This issue is more related to Typescript than Angular. It seems like you have specified the injection using the "BaseRestService" type in the consumers, right?

If that's the case, you won't be able to access the methods of the children.

One solution could be creating an interface for the common methods in the children, and then using a factory to generate the children based on certain criteria. There are also other injection techniques you can explore.

Another approach could be implementing a mixin, which might achieve what you're looking for in a different way.

Check out https://www.typescriptlang.org/docs/handbook/mixins.html for more information.

Answer №2

Just encountered a similar issue and decided to update from Angular Version 6.1 to 7.0. Surprisingly, that solved the problem for me!

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

Here is a way to return a 400 response in `express.js` when the JSON request body is invalid

How can I make my application send a response with status code 400 instead of throwing an error if the request body contains invalid JSON? import express from 'express' app.use(express.urlencoded({ extended: false })) app.use(express.json()) ...

Guide to customizing the layout preview specifically for certain components in Storybook, without affecting all components

Currently working on my storybook project and facing an issue. I'm aiming to have the layout centered in the preview section. I attempted export const parameters = { layout: 'centered', }; in the .storybook/preview.js file However, this c ...

What is the best way to organize an array both alphabetically and by the length of its elements?

Imagine I am working with an array like this: ['a', 'c', 'bb', 'aaa', 'bbb', 'aa']. My goal is to sort it in the following order: aaa, aa, a, bbb, bb, c. this.array= this.array.sort((n1, n2) => ...

Excluding properties based on type in Typescript using the Omit or Exclude utility types

I am looking to create a new type that selectively inherits properties from a parent type based on the data types of those properties. For instance, I aim to define a Post type that comprises only string values. type Post = { id: string; title: string ...

Developing in TypeScript with styled-components allows for seamless integration between

New to TypeScript and seeking guidance. I currently have a component utilizing styled-components that I want to transition to TypeScript. import React from 'react' import PropTypes from 'prop-types' import styled from 'styled-comp ...

There seems to be an issue with executing an imported function from a .ts file within a TSX file in NextJs, resulting

I've encountered an issue that seems to be related to using NextJs with TypeScript. For example: // /pages/index.tsx import _ from 'lodash' export const MyComponent = () => { return ( <ul> { _.map(someArray, ...

Is there a way to access the value of an IPC message beyond just using console log?

I am developing an app using electron and angular where I need to send locally stored information from my computer. I have successfully managed to send a message from the electron side to the angular side at the right time. However, I am facing issues acce ...

Errors arose due to the deployment of TypeScript decorators

Using TypeScript in a brand new ASP.NET Core project has brought some challenges. We are actively incorporating decorators into our codebase. However, this integration is causing numerous errors to appear in the output of VS2015: Error TS1219 Experim ...

What is the process for retrieving information from a retail outlet?

How can I retrieve data from the Vuex store using Vue.js? Below is my code: Vue.use(Vuex); export default new Vuex.Store({ modules: { data } }) data.js import axios from 'axios'; const state = { data: '' }; cons ...

What is the best way to update the mat-tab when the routeParameters are modified?

I need to reinitialize the mat-tab-group in order to make the first tab active when there is a change in the routeParams. ts file: public index = 0; ngOnInit() { this.subscription = this.route.params.subscribe((routeParams: Params) => { // some ...

Navigating the complexities of managing numerous checkboxes in React

I am a beginner with react and recently received a task to complete. The requirements are: Show multiple checkboxes. The order of checkbox names may change in the future, allowing the client to decide the display order. Display checkboxes based on their a ...

Type of event target MouseEvent

I am currently working on a custom hook const hasIgnoredClass = (element: Element, ignoredClass: string) => (element.correspondingElement ? element.correspondingElement : element ).classList.contains(ignoredClass); const isInIgnoredElement = ( ...

Utilize a generic data type for a property that can accept values of type 'number', 'string', or 'undefined'

This query involves React code but pertains to typescript rather than react. To simplify, I have a component called MyList which accepts a single generic type argument passed to the props type. The generic type represents an object that will be used to c ...

What is the best way to assign the value of an HTTP GET request to a subarray in Angular 8

Attempting to store data in a sub-array (nested array) but despite receiving good response data, the values are not being pushed into the subarray. Instead, an empty array is returned. for (var j=0;j<this.imagesdataarray.length;j++){ this.http.g ...

Modifying variable assignments in an Angular index.html file according to the environment

Is it possible to dynamically set the config.apiKey value in Angular based on different environments such as Development and Production? In a Production environment, use config.appKey = 'AB-AAB-AAB-MPR'; In a Development environment, use config ...

What is the best method to condense an array or extract only the valid values?

Looking to find the total count of properties that are true from an array of objects? Here's an example: let data = [ { comment: true, attachment: true, actionPlan: true }, { whenValue: '', ...

Achieving intellisense functionality in TypeScript without the use of classes

Just dipped my toes into TypeScript, attempting to convert this basic JavaScript code to TypeScript. Here is the JavaScript code snippet: Item = {} Item.buy = function (id) {} Item.sell = function (id) {} I prefer not to use classes and would like to ut ...

What is the best way to extract values from case-sensitive query param variables?

I am dealing with a URL that contains the query string id. However, the variable id can appear as either 'id' or 'Id' in the URL. From my understanding, these two variations will be treated differently. To handle URLs like the followin ...

What is the best way to disable a submit button based on form validity in Angular 4 with ng-content?

Include a form component that consists of an email field, password field, and submit button passed through ng-content. This allows the login form to display a 'Login' button and the register form to display a 'Register' button. Here is ...

Angular 10: Customize Paypal button to open a new window when selecting "Pay by debit or credit card" option

In my Angular 10 app, I have successfully implemented a Paypal button. However, there is an issue where the "Paypal" button opens a new window while the "Pay by debit or credit card" option opens an inline form. This behavior mirrors what is seen at https: ...