What are the best scenarios for implementing abstraction in Angular?

Throughout my experience, I have encountered Java EE, .Net, and various other enterprise application architectures. In each case, there was always an abstract upper class - like AbstractService for generalizing the service layer.

However, in Angular, I haven't come across something similar. Even though it does have a standardized service/api layer.

I'm curious if not using abstract classes in TypeScript could be considered a bad practice since ultimately it compiles down to JavaScript. Or is it simply because there aren't many tutorials or guidelines covering this level of abstraction? It's a bit perplexing to me.

Answer №1

There are various practical applications for abstract classes within Angular, with one of the main uses being abstract classes utilized as dependency injection tokens

Dependency Injection Token (implements)

export abstract class AbstractEventService {
  dispatchEvent(event: any): void;
  listen(event: any): Observable<any>;
}

// Implementing the abstract class as interfaces
export class EventService implements AbstractEventService {
   // The compiler will enforce the implementation of dispatchEvent() and listen()
}

// Using the abstract class as a DI token (which cannot be done with interfaces)
providers: [provide: AbstractEventService , useClass: EventService ]

This method is especially beneficial for unit testing. You can override in TestBed.configureTestingModule() or TestBed.overrideProvider()

Service Base Classes (extends)

While this approach may not be as commonly seen in tutorials or demonstrations, it is prevalent in real-world applications

export abstract class AbstractBaseService {
   // Extending classes must implement these properties/functions
   protected abstract serviceID: string;
   protected abstract provideInitialState(): IState;

   protected formatResponse(response: IAccountResponse): IFormattedResponse {
       // Logic accessible to subclasses
       // Override if necessary
   }
}

export class AccountService extends AbstractBaseService {
   // Implementing abstract properties and functions
   // Override protected/private properties and functions as needed
}

Notes

You'll notice that I discuss overriding protected/private properties and functions - TypeScript has limitations in this aspect, allowing the overriding of all Abstract class properties and functions

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

Customizing output paths for script files in angular.json with Angular

Is there a way to set up the configuration in angular.json so that script files are output as shown in the directory tree below? Note: The file aaa.js has been renamed from main.js /assets/js/aaa.js ...

Is it possible for Angular's ngStyle to accept multiple functions? If not, what is the alternative solution?

Can multiple conditions be added to different attributes with ngStyle? Is it possible to change text color and background color based on specific JSON values using ngStyle? About the Project: I am currently working on creating a tab bar that resembles a ...

Looking to categorize and sum the values within an array of objects using JavaScript?

I'm looking to optimize this response data within my Angular application. res=[ { "url": "/page1", "views": 2 }, { "url": "/page2", "views": 1 }, { "url": "/page1", "views": 10 }, { "url": "/page2", "views": 4 }, { "url": "/page3", "views": 1 }, ...

Ways to modify this request in order to update the current status

How can I optimize these calls to avoid repeating the same sentence for refreshing the state? I'm not looking for a major overhaul, just some suggestions like putting this call inside a function and invoking it when needed... export const CategoriesPa ...

Printing error stack that includes the source from the source map

I've been trying to take advantage of the native support for source maps in Node, but I'm having trouble getting them to work when printing errors to the console. Despite running node with --enable-source-maps and using the source-map-support pa ...

After using apt to install tsc, I find myself in a dilemma on how to either delete or upgrade it

After realizing I was missing Typescript on my server, I attempted to run the 'tsc' command. However, I received a message suggesting I use 'apt install tsc' instead. Without much thought, I executed the command. Normally, I would insta ...

Incorporating type declarations for a basic function that returns a wrapper function for other functions

In my vanilla JS code, I have a sophisticated function that is exported and I am attempting to create a .d.ts file for it. Unfortunately, my previous attempts at writing the .d.ts file have not been successful in passing the types from one stage of the fu ...

Eliminating Body Tag Margin in Angular 4: A Step-by-Step Guide

In the Angular 4 project, the app.component.html file does not include a body tag that can be styled to eliminate the padding associated with the body tag. An attempt was made in the app.component.css file to remove the margin with the following code, but ...

Vue.js - A dynamic parent component generates content based on data passed from a renderless child component

I am currently working on developing a system for generating buttons using vue 3 and vue-class-component. The main goal is to create a flexible button generation process, where the number of buttons generated can vary (it could be just one or multiple). Us ...

While running tslint in an angular unit test, an error was encountered stating 'unused expression, expected an assignment or function call'

Is there a method to resolve this issue without needing to insert an ignore directive in the file? Error encountered during command execution: ./node_modules/tslint/bin/tslint -p src/tsconfig.json --type-check src/app/app.component.spec.ts [21, 5]: unuse ...

"Exploring the dynamic duo of Angular2 and ng2Material

I am currently facing an issue with the styling in my code while using ng2Material with Angular2. First: A demonstration of Material style functioning properly can be seen in this plunker. When you click on the button, you will notice an animation effect. ...

What is the best approach for unit testing with a subscribe in Angular 5?

import { Component, Input, OnInit } from '@angular/core'; import {DataplansDetails} from '../../models/dataplans-details'; import * as _ from "lodash"; @Component({ selector: 'jsonform', templateUrl: './jsonform.comp ...

Is there a built-in feature in npm or yarn that automatically installs @types when they are present in Typescript projects?

Is there a feature in npm or yarn that automatically installs @types/* for packages without their own types, in Typescript projects? For example: //package.json { // ... "installTypes": true } // installing package yarn add ABC <- will install A ...

We are unable to update the document in AngularFire as the document reference ID could not be retrieved

I am currently working on an update function that is designed to retrieve a specific document based on its unique document uid, which is connected to the authenticated user's uid. In another part of my code, I have a function that successfully fetche ...

Forcing locale in Angular 2: A step-by-step guide

I recently developed a compact application with Angular2 and incorporated the currency pipe. I noticed that the currency is automatically formatted based on my browser's language. Is there a way for me to customize or override this default behavior? ...

Angular: "btn" class vanishes when the button is toggled

I am facing an issue with the button's class change functionality. I am using the [ngClass] directive to switch between Bootstrap classes for the button style. However, when I click the button, the "btn" class seems to disappear from the code. Instead ...

Determine through programming whether an ng-content slot has been filled in Angular

I have developed a dynamic Angular component that utilizes content projection and slots in the following way: <div class="content-wrapper"> <div class="short-wrapper" [style.opacity]="expanded ? 0 : 1"> ...

Clicking on the <Link to=URL> in a React application built with Typescript and Redux triggers the disappearance of the component

Issue Background The application was created using npx create-react-app rrts --typescript, which sets up React, Redux, and Typescript. Problem Visualization (Content is the component with sentences) View Problem Image Here Problem Description Clicking o ...

Angular does not display B64 images

I am trying to show a Base64 image string in an Angular application. When I use a static image string, it displays correctly. However, when the image is dynamic, some issues arise. Below is the code from my component.ts file: this.Socket_io = socketIo(&ap ...

Using React.ReactNode as an argument in Storybook

This is a unique button component type that I have created import React from 'react' export type ButtonProps = { label: string; color?:'primary' | 'secondary' | 'tertiary'; size?:'mobile' | 'tabl ...