What is the best way to integrate a service-defined class into a component in Angular?

Is there a way to utilize a class that is defined in a service within a component? The Service.ts file includes a class that I would like to use in my component. Despite injecting the service into the component, I am encountering difficulties in accessing the class.

**Below is a snippet from my service.ts file


    import { Injectable } from '@angular/core';

    @Injectable({
      providedIn: 'root'
    })
    class Registration{
      constructor(
       public id: number = null,
      public name: string = '',
      public age:number=null,
      public dept: string = 'Select Your Department',
      public  empType: string = 'Select Employee Type',
      public hra: string = '',
      public medical:string='',
      ) {}
      }

    export class DataService {
      registrations: Registration[] = [];
      myModal: Registration;
      showNew: Boolean = false;
      submitType: string = 'Save';
      selectedRow: number;
      empType: string[] = ['Permanent','Trainee'];

      constructor() { }
    }

//Now, I want to use the Registration Class in my Component File.

import { Component, OnInit, ViewChild } from '@angular/core';
import { DataService } from '../data.service';



@Component({
  selector: 'app-registration',
  templateUrl: './registration.component.html',
  styleUrls: ['./registration.component.css']
})
export class RegistrationComponent implements OnInit {
  @ViewChild('myModal') myModal: any;
  // It holds a list of Registrations
  registrations: Registration[] = [];
  // It holds registration Model
  regModel: Registration;
  // It signifies whether the operation is 'Save' or 'Update'.
  submitType: string = 'Save';
  // It keeps track of the table row index based on selection.
  selectedRow: number;
  // It maintains an Array of Employee Types.
  employeeType: string[] = ['Permanent', 'Trainee'];
  //It maintains the department Types
  department: string[] = ['PES', 'AP1', 'AP2', 'CSD', 'QSD', 'ADMIN'];
  constructor(private data: DataService) {
    // Add default registration data.
    //this.registrations.push(new Registration('Johan', 28, 'PES', 'Permanent', '5', '10'));

  }

  ngOnInit() { }

  // The following method is linked to the New Button.
  onNew() {
    // Initialize a new registration.
    this.regModel = new Registration();
    // Change submitType to 'Save'.
    this.submitType = 'Save';
    // display the registration entry section.
   // this.showNew = true;
  }

  // The following method is linked to the Save Button.
  onSave() {

    if (this.submitType === 'Save') {

      // Push registration model object into registration list.
      (() => {
        confirm("Press OK , If You Want To Save !");
        console.log('Data Saved');
        this.myModal.nativeElement.click();
      })();

      this.registrations.push(this.regModel);

    } else {
      // Update the existing properties values based on model.
      this.registrations[this.selectedRow].name = this.regModel.name;
      this.registrations[this.selectedRow].age = this.regModel.age;
      this.registrations[this.selectedRow].dept = this.regModel.dept;
      this.registrations[this.selectedRow].empType = this.regModel.empType;
      this.registrations[this.selectedRow].hra = this.regModel.hra;
      this.registrations[this.selectedRow].medical = this.regModel.medical;

      if(this.myModal)
        this.myModal.nativeElement.click();
    }
    // Hide the registration entry section.
    //this.showNew = false;
  }

  // The following method is linked to the Edit Button.
  onEdit(index: number) {
    // Assign the selected table row index.
    this.selectedRow = index;
    // Initialize a new registration.
    this.regModel = new Registration();
    // Retrieve the selected registration from the list and assign it to the model.
    this.regModel = Object.assign({}, this.registrations[this.selectedRow]);
    // Change submitType to Update.
    this.submitType = 'Update';
    //this.showNew = true;
  }

}**

Answer №1

In order to make a class accessible outside of its file, you must utilize the export keyword, just like you did for the DataService.

It is recommended to place your @Injectable declaration below the Registration class. For better organization, consider storing each class definition in its own separate file:

export class Registration {
  // ...
}

@Injectable({
  providedIn: 'root'
})
export class DataService {
  // ...
}

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

Oops! The Element Type provided is not valid - it should be a string

I have a desire to transition from using Victory Native to Victory Native XL. However, I am encountering an error message saying Render Error Element type is invalid. import * as React from "react"; import { View } from "react-native"; ...

The argument type 'MatSort | null' cannot be assigned to the parameter type 'MatSort' in this scenario

When attempting to retrieve sorted data from MatTableDataSource, I used the following code: this.source = this.dataSource.sortData(this.dataSource.filteredData,this.dataSource.sort); Unfortunately, I encountered an error message: Argument of type ' ...

Efficiently resolving Angular's ngFor issues with Float functionality

I am currently developing a rating system that allows for half-star ratings, such as 3.5 or 4.5. Below is the code I have written: <div class="rating"> <i class="icon-star voted" *ngFor="let j of Arr(item.nbEtoile); let i = index;"></i& ...

What are the steps to incorporating the pick function in TypeScript?

The TypeScript documentation mentions a pick function that is declared but not implemented. In an attempt to create a simplified version, I wrote the following: function pick<T, K extends keyof T>(obj: T, key: K): Pick<T, K> { return { [key]: ...

A guide to efficiently removing an element in Angular using TypeScript by considering certain properties

I need help removing an element from an array based on any property such as its key, name, or email. HTML <tr *ngFor="let person of persons;" (click)="remove(person.key)"> <td>{{person.key}}</td> <td>{{person.name}}</td> ...

Retrieve active route information from another component

We are utilizing a component (ka-cockpit-panel) that is not linked to any route and manually inserted into another component like so: .. ... <section class="ka-cockpit-panel cockpit-1 pull-left"> <ka-cockpit-panel></ka- ...

Angular is hindered from updating due to its reliance on TypeScript dependencies

My Ionic info is as follows: Ionic CLI : 6.2.1 (C:\Users\Arashsoft\AppData\Roaming\npm\node_modules\@ionic\cli) Ionic Framework : @ionic/angular 5.0.5 @angular-devkit/build-angular ...

Angular downgrades from version 13.3.8 to 13.3.7

When I input the command: ng v I am shown the version as "Angular: 13.3.8" in the image. Can someone explain where this version is coming from and how can I change it back to 13.3.7? Furthermore, I noticed that the packages listed in the screenshot are d ...

What could be causing the import alias issue in the latest version of Next.js, version 12

Below are my CompileOptions: { "compilerOptions": { "target": "es5", "lib": ["dom", "dom.iterable", "esnext"], "allowJs": false, "skipLibCheck": tr ...

When utilizing TS Union Types from an Array, the resulting type will consistently be a

After reading this response, I decided to create some union types from a string[] in order to return a list of valid type values. However, instead of that, the type ends up accepting any string value. const arrayDays = Array.from(Array(32).keys(), (num) =& ...

Troubleshooting Office-Js Add-ins using Angular-CLI and F12chooser: Map files not visible

When I first started developing Office Add-ins, I was using Angular with Webpack. Now, however, I am eager to try it out with Angular-CLI. Everything seems to be working fine, except for one thing: F12Chooser Debugging Previously, I was able to debug my ...

Guide to creating JSDoc for a TouchEvent handler

Looking to improve my shorter-js codebase with JSDoc for TypeScript definitions, but hitting a roadblock. I've implemented the on() function using Element.addEventListener, working well so far. However, when passing a TouchEvent as a parameter for an ...

Optimal method for consecutively making N number of API calls in Angular 9 in a synchronous manner

Having a service method for API calls structured as follows: getUsers(id){ return this.http.get(`${env.apiURL}/id`) } Now, the requirement is to call this method for a list of users stored in an array: userId=[1,2,3,4,5,6,7,8,9] The goal is to retrieve ...

Tooltip implementation in Angular side bar is malfunctioning

I have integrated my angular 7 project side bar with a Tooltip from Angular Material, but I am facing issues with it not working properly. Can anyone guide me on how to correctly add the Tooltip functionality? Thank you. sidebar.component.html <ul cl ...

Guide to upgrading ag-grid-community from 20.1.0 to 24.1.0

I'm currently encountering some errors that I can't seem to find in the AgGrid documentation. These attributes are not mentioned anywhere, not even in the Change Log. First off, these compilation errors are popping up: ERROR in : Can't bind ...

Creating a connection between properties and their values

I am looking to implement a property for data binding on my own terms. For instance, consider the following list of items: [{name='name1', invalid='error.name1'}] Along with another list of errors. errors : any= ['name1': & ...

Exploring Angular: How to access ViewChild from a dynamically loaded component

One of my components includes a ViewChild element like this: @ViewChild('overView') content: ElementRef; I am dynamically loading this component in the following way: let overviewComponent = this.vcr.createComponent(OverviewComponent); let conte ...

Challenge with Routing in Angular 2

I'm dealing with a route setup like this: path: 'something/:id/somethingElse' In my header.component.html, I need to include a link to this page. I tried the following approach: <a routerLink="['something',myIdThatIsDynamicO ...

Trouble with Typescript in VSCode made easy

Setting up a VSCode environment for working with TypeScript v2.03 has been challenging. Beginning with a simple vanilla javascript snippet that can be tested in node via the integrated terminal. function Person() { this.name = ""; } Person.prototy ...

Having difficulty installing TypeScript on my machine

https://i.stack.imgur.com/l6COf.pngHaving trouble installing TypeScript with the following error: npm WARN registry Using outdated package data from https://registry.npmjs.org/ due to an error during revalidation. npm ERR! code E500 npm ERR! 500 Interna ...