What separates an abstract class with implemented method from a service in Angular?

In this scenario, we have an abstract class with an implemented method that the HomeComponent extends, and a service with the same code that we inject into the component. Are there any differences in our case? If so, what are the differences? If not, when should we use an abstract class versus a service?

abstract class Base {
    name: string = "";

    getName(){
       return this.name;
    }
} 


 @Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent extends Base implements OnInit {


}

vs

@Injectable()
export class BaseService {
    name: string = "";

    getName(){
       return this.name;
    }
}

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css'],
  providers: [BaseService]
})
export class HomeComponent implements OnInit {

    constructor(private baseService: BaseService) {}

}

Answer №1

When creating abstract classes, the main purpose is to serve as a foundation for other classes to build upon. Abstract classes cannot be instantiated on their own. By extending a class, whether it is abstract or not, you inherit all its properties and can access them directly in the extending class. For example, accessing the getName method can be done like this:

 @Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent extends Base implements OnInit {
  constructor(){
     super();
     this.getName();
  }
}

If the base class is made injectable, then it needs to be accessed from an instance of that injected class. It's important to note that making a class Injectable turns it into a singleton with consistent state across all instances where it's provided, whereas extending an abstract base class ties it to the specific extending class.

Additionally, abstract classes cannot be Injectable. The decision of when to use abstract classes versus Injectable classes depends on your project goals. Abstract classes are useful for organizing code in an Object-Oriented Programming (OOP) manner, while injecting a class is suitable for sharing a base class among different injections.

To learn more about abstract classes, visit https://www.typescriptlang.org/docs/handbook/2/classes.html#abstract-classes-and-members

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

What's the best way to import a file from OneDrive to an Angular app using Typescript?

I am currently working on an Angular application that utilizes OneDrive/Sharepoint for file storage. Authentication is functioning properly, and I can successfully save files. However, I am encountering an issue when attempting to download a file created a ...

Eslint for Typescript in Vue is throwing an error with a message "Unexpected token, expecting ','. Make sure to

Whenever I attempted to utilize vue's type assertion, I kept encountering this eslint error. To illustrate, consider the following snippet: data: function () { return { sellerIdToListings: {} as any, // 'as' Unexpected to ...

Tips for Angular4: ensuring ngOnDestroy completion before navigation

My task involves managing a list of objects where the user can choose an object to edit using a child component. However, when the user returns to the list component, the child component needs to clean up in the ngOnDestroy method, which includes making a ...

Troubleshooting ngFor in Angular 5

I'm currently working on a component that needs to display data fetched from the server. export class CommerceComponent implements OnInit { dealList; ngOnInit() { this.getDeals(); } getDeals(){ this.gatewayService.se ...

TypeScript encounters a self-referencing type alias circularly

Encountering an issue with Typescript 3.6.3, specifically getting the error: Type alias 'JSONValue' circularly references itself. View code online here In need of assistance to resolve the circular reference in this specific version of TS (note ...

Issues arise when attempting to construct an angular docker image

After attempting to create an angular docker image, I encountered the following error message following the execution of npm run build --prod: executor failed running [/bin/sh -c npm run build --prod]: exit code: 1 I am seeking clarification on this iss ...

Stop Uploading: Multer, MongoDB

My search for current solutions on canceling file uploads with Mongo, NodeJS & Angular has been fruitless. Existing tutorials only cover how to delete a file, which is not what I need. My goal is to provide users with the ability to halt the file upload pr ...

Is your Express router failing to handle post requests properly?

I've set up my development environment using angular-cli and webpack, with the following configuration in package.json: "dependencies": { "@angular/common": "^4.0.0", "@angular/compiler": "^4.0.0", "@angular/core": "^4.0.0", "@angular ...

Retrieving images in Angular 2 from a file upload process

Hello in my Angular 2 application I am integrating ng2-file-upload library for file uploading: <input type="file" ng2FileSelect [uploader]="uploader" multiple (change)="onChange($event)"> I am interested in creating an instance of an image object ...

What is the reason for allowing var to declare duplicates, while const and let restrict duplicate declarations?

What is the reason behind var allowing duplicate declaration while const and let do not? var allows for duplicate declarations: xx=1; xx=2; console.log(xx+xx);//4 var xx=1; var xx=2; console.log(xx+xx);//4 However, let and const do not allow for dupl ...

Tips for resolving the issue of "The types 'GameState' and 'string' do not intersect, so this condition will always yield 'false'."

I need to display different components based on the value of gameStatus: import React from "react"; import { useAppSelector } from "./hooks/redux"; import EndScreen from "./pages/EndScreen"; import QuestionsPage from "./p ...

Importing TweenLite in Typescript is a breeze

After downloading the GSAP package via npm, I am keen on importing the TweenLite class to my TypeScript app. While importing all of GSAP can be achieved by using require('gsap'); and it functions correctly, this method does not work in TypeScript ...

Retrieving data from Typescript enums using strings

I need assistance extracting values from this enum: enum Sizes { Tiny = "Tiny", VerySmall = "Very Small", Small = "Small", Medium = "Medium", Large = "Large", VeryLarge = "Very Large" } Although I followed recommendations from other sources, ...

What is the process of creating a new array by grouping data from an existing array based on their respective IDs?

Here is the initial array object that I have: const data = [ { "order_id":"ORDCUTHIUJ", "branch_code":"MVPA", "total_amt":199500, "product_details":[ { ...

$(...).parentElement is not a function - Troubleshooting a Problem with WebDriver IO and TypeScript

Alright, the objective is simple. I need to ascend from the root to obtain its parent element. Following the webdriver documentation, it should resemble something like this: it('should retrieve the class from the parent element', async () => { ...

By default, the radio button in Angular2 does not seem to be checked upon page load

When loading a form with two radio buttons labeled Yes and No, I want to make sure that the default selection is No. In the HTML code: <md-radio-group> <md-radio-input #rdoYes [value]="true">Yes</md-radio-input> <md-radio-input #rd ...

typescript for creating personalized theme based styled components

After conducting some research online, I have experimented with two different methods to achieve typing for a custom theme in a React Native project using TypeScript and Expo. I created a declaration ts file and included it in my tsconfig. Below is an over ...

Sorting through an array of JSON data

Hi there, I'm currently following a guide and I'm having some trouble getting it to work for me. I'm fairly new to Angular so I'm sure it's just a simple issue. Can anyone lend a hand? Initially, all the JSON objects show up on th ...

concerning the integration of CSRF token in the GuestPayment feature

Greetings and thank you for taking the time to help me out. I am currently working on a project in AngularJS 2.0 where users need to be able to pay their pending bills through a GuestPayment portal. This portal does not require any login credentials and ...

Is it advisable to reuse encapsulated constants during unit testing and if so, what is the best

Hey there, I'm currently working on a unit test for a function. While the technical details are not crucial, I thought it would be helpful to provide some code snippets for better understanding. Check out the function below: export function getSalu ...