Exploring the capabilities of extending angular components through multiple inheritance

Two base classes are defined as follows:

 export class EmployeeSearch(){

    constructor(
        public employeeService: EmployeeService,
        public mobileFormatPipe: MobileFormatPipe
    )

    searchEmployeeById();

    searchEmployeeByName();
}

export class EmployerSearch(){

    constructor(
        public employerService: EmployerService,
        public mobileFormatPipe: MobileFormatPipe,
        public employerNamePipe: EmployerNamePipe
    )

    getAllEmployers(){

    }

    getLocalEmployers(){

    }
} 

A component class needs to make use of the above two classes.

export class addNewEmployeeComponent(){

    constructor(){

    }
}

An attempt was made to use the applyMixins solution for extending multiple classes, but the definition of super() for the base class while extending two classes is unclear. An error was encountered when trying to use the AddNewEmployee mixin in the component.

import { EmployeeSearch } from './employee-search';
import { EmployerSearch } from './employer-search';

export class  AddNewEmployee{

}
export interface AddNewEmployee extends EmployeeSearch, EmployerSearch{

}

function applyMixins(derivedCtor: any, baseCtors: any[]) {
    baseCtors.forEach(baseCtor => {
      Object.getOwnPropertyNames(baseCtor.prototype).forEach(name => {
        Object.defineProperty(derivedCtor.prototype, name, Object.getOwnPropertyDescriptor(baseCtor.prototype, name));
      });
    });
  }

applyMixins(SearchPatient, [PatientSearch, DepartmentDoctorSelect]);

A mixin was created with the given code, but it is unclear how the AddNewEmployee class can be used in the AddNewEmployeeComponent.

The situation involves the need to use two classes in a component, but multiple inheritance is not an option. Any alternative solutions are welcome.

A reference was made to this question but the accepted answer was not fully understood.

Thank you!

Answer №1

To utilize the classes without inheriting from them, you can simply declare EmployeeSearch and EmployerSearch as services like this:

@Injectable({
  providedIn: 'root',
})
// remember that you don't need `()` here
export class EmployeeSearch {
    
    constructor(
        public employeeService: EmployeeService,
        public mobileFormatPipe: MobileFormatPipe
    )

    searchEmployeeById();
    
    searchEmployeeByName();
}

After declaring them, you can easily use them in your service or component.

import { EmployeeSearch } from './employee-search';
import { EmployerSearch } from './employer-search';

// if you require them in another service
@Injectable({
  providedIn: 'root',
})
export class EmployeeService {
    
    constructor(
        private employeeSearch: EmployeeSearch,
        private employerSearch: EmployerSearch
    ) { }

    fancyBusinessMethod(employeeID: number) {
        const employee = this.employeeSearch.searchEmployeeById(employeeID);
        // ...
    }
}

// if you require them in a component
@Component({
  selector: 'app-emp',
  templateUrl: `
<div>
  <p *ngFor="let emp of employees">{{ emp.name }}</p>
</div>
`,
  styleUrls: []
})
export class EmployeeComponent {
    
    public employees: Employee[] = [];
    
    constructor(
        private employeeSearch: EmployeeSearch,
        private employerSearch: EmployerSearch
    ) { }
    
    onEmpSearch(id: number) {
        this.employees = this.employeeSearch.searchEmployeeById(employeeID);
    }
    

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

Unable to loop through the data using forEach method as it is not a function. Can anyone guide me on how to

Currently, I am working on an angular project that involves retrieving data from a JSON object. Typically, in such cases, I would create a class like 'fake.ts' to fetch and access the correct values. However, in this instance, the JSON contains 4 ...

Looking for help with setting up Nodemailer and installing it via NPM

I am currently developing a mobile application using Ionic with Angular/Typescript, and I'm in need of a front-end solution to dynamically send emails in the background to a specific email address. I tried using emailjs, but it requires JavaScript whi ...

Facing issues with the template URL not functioning properly during the migration from Angular 1.5 to Angular 6

I am currently in the process of migrating an Angular 1.5 project to Angular 6, but I've encountered an issue with the templateUrl not working in the Angular 1.5 component. The packages I am using are: Angular CLI 6.0.8 TypeScript 2.7.2 Angular 6.0.7 ...

Displaying data from an Angular subscription in a user interface form

I am attempting to transfer these item details to a form, but I keep encountering undefined values for this.itemDetails.item1Qty, etc. My goal is to display them in the Form UI. this.wareHouseGroup = this.formBuilder.group({ id: this.formBuilder.contr ...

Is there a way to modify the background of a div when a specific field within my component is true and the div is being hovered over?

When I hover over a div, I want the background color to change. Additionally, I need the color choice to be based on an element within my component. <div *ngFor="let u of users;" [style:hover.background-color] = "u.selected ? 'red ...

Troubleshooting the tabindex issue with buttons in MatMenu in Angular

I am currently using Angular 17 in my project and I am working on adding ADA compliance to it by placing tabindex where needed. However, I am encountering an issue with a button inside a mat menu. The tabindex="0" attribute is not focusing on th ...

Tips for preserving updates following modifications in Angular 5/6?

I'm currently working on enhancing the account information page by implementing a feature that allows users to edit and save their details, such as their name. However, I am encountering an issue where the old name persists after making changes. Below ...

What could be causing my TypeScript project to only fail in VScode?

After taking a several-week break from my TypeScript-based open-source project, I have returned to fix a bug. However, when running the project in VScode, it suddenly fails and presents legitimate errors that need fixing. What's puzzling is why these ...

Tips for effectively narrowing the `undefined` type

Why am I getting this error message? const func = (a: unknown) => { if (a && typeof a === 'object' && 'b' in a) { a.b; } }; The error message I'm receiving is: Property 'b' does not exist on ty ...

Encountered an issue while attempting to convert a vue-cli project to TypeScript

I am currently attempting to migrate my vue-cli project to typescript. According to this resource, all I need to do is execute the following command: vue add typescript My project is being run on a Windows machine using Git Bash However, when I try to ru ...

Module logo.svg not found? Error in Typescript

Integrating package: vue-svg-loader. Established the file svg.d.ts with the content below: declare module '*.svg' { const content: any export default content } Utilizing it in a component in the following manner: import register from &apo ...

Dynamic Angular form with nested elements

Need help creating a nested form following the example from angular.io documentation: https://stackblitz.com/angular/pbdkbbnmrdg The objective is to include two DropdownQuestion elements from question.service.ts within a child formgroup called "details", ...

"Encountering a glitch in the Typescript/Node API where Express routes

Encountering a peculiar issue here - when attempting to import my router from an external file and add it as a route, I keep getting this unusual error where the string appears to be enclosed in double quotes. https://i.sstatic.net/nm9Wn.png ...

Error message: Typescript and Styled-Component conflict: GlobalStylesProps does not share any properties with type { theme?: DefaultTheme | undefined; }

I've encountered an issue while passing props inside GlobalStyles in the preview.js file of my storybook. The props successfully remove the background from the default theme, but I'm receiving an error from Typescript: The error message states " ...

Ways to enable components to access a string dependency token

I'm currently developing an Angular application that utilizes Angular Universal for server-side rendering functionality. One interesting aspect of my project involves passing a string dependency token as a provider within the providers array in serve ...

Troubleshooting npm installation issues with Angular 2 Quickstart guide (URL: https://angular.io/docs/js/latest/quickstart.html)

I am currently facing issues when trying to set up Angular 2 on my Ubuntu 15.10 system. Despite multiple attempts, the installation fails and I receive error messages. Even after attempting to install Angular 2 using the npm package command sudo npm insta ...

Angular 2: Dealing with Missing Image Loading

When viewing an HTML file containing the following code: <div> <img src="New-Google-Logo.png"/> </div> The image file New-Google-Logo.png is expected to load from the same folder as the HTML file. However, after running ng s ...

Use Angular's super.ngOnDestroy method for handling cleanup/unsubscribing

When it comes to unsubscribing / cleaning up from observables in Angular components (using ngOnDestroy), there are multiple options available. Which option should be considered the most preferable and why? Also, is it a good practice to include super.ngOnD ...

Apologies, but there was an error attempting to differentiate 'nombreyo'. Please note that only arrays and iterables are permitted for this action

Encountering an error while attempting to display a class in the HTML. <li> <ul> <li *ngFor="let refac of refactormodel" > -- word_to_rename: {{refac.word_to_rename}} -- renowned_word: {{refac.renowned_word}} ...

Generating a form structure from json containing repeated inputs: Control with path formArray could not be located

Currently, I am in the process of constructing a form using JSON data. My backend is implemented with Spring Boot, which returns the following object to an Angular frontend: { "controls": [ { "name": "genre", ...