Develop instances from a class in Angular 2

Hello there! I have a question about creating a class that implements an interface and utilizes data from a .get service to instantiate a new object. Here is an example of what I'm trying to achieve:

import { Component, OnInit } from '@angular/core';
import { User} from '../interfaces/user';
import {UserService} from '../services/user.service';
import { UserClass } from  '../classes/user-class'

@Component({
  selector: 'up-pros',
  templateUrl: './pros.component.html',
  providers: [UserService]
})
export class ProsComponent implements OnInit {
  public users :User[];
  public term: string;
  constructor(private _httpService: UserService) { }

  ngOnInit() {
    console.log(UserClass)
    this.term= 'INSTRUCTOR';
    this._httpService.searchUsers(this.term)
        .subscribe(
          data => {this.users = new UserClass(data), console.log(data)},
          error => alert(error + ' Error Get')
        );
  }
}

In the above code snippet, you can see how the UserClass is implemented:

import { User } from '../interfaces/user';
import { Address } from "../interfaces/address";

export class UserClass implements User {

public  id:           number
public  name:         string
public  password:     string
...
...

}

And here is the interface definition for User:

import { Address } from "./address"

export interface User {
  name:       string;
  password:   string;
  lastNameA:  string;
  ...
  ...
}

However, when attempting to use this implementation in the pros-component.ts file, I encountered the following error message:

Supplied parameters do not match any signature of call target.
[default] Checking finished with 1 errors

This issue might be related to my service setup. Here's a look at the UserService:

import {Injectable} from '@angular/core';
import {Http, Headers} from '@angular/http';
...
...

Answer №1

If the data structure aligns with the UserClass list, you can easily execute:

this._httpService.findUsers(this.term)
        .subscribe(
          result => {
                      this.users = result as User[];
                      console.log(result)
                  },
          error => alert(error + ' Error Retrieving')
        );

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

Creating a stacked bar chart in Kendo UI Angular is a simple and effective way to visualize

Recently diving into Angular, I've encountered an issue while trying to generate stack bar charts using Kendo UI. Instead of the desired stacked bars, I'm ending up with regular bar charts even after implementing stack="true". The stack ...

What might be the reason why the custom markers on the HERE map are not displaying in Angular?

I'm having trouble displaying custom icons on HERE maps. Despite not receiving any errors, the icons are not showing up as expected. I have created a demo at the following link for reference: https://stackblitz.com/edit/angular-ivy-zp8fy5?file=src%2Fa ...

The TypeScript compiler does not transpile the .at() function

While converting TypeScript to JavaScript compatible with NodeJS v14 using the provided configuration: { "compilerOptions": { "lib": ["es2020"], "rootDir": "src", "outDir": "bui ...

Opt for ion-select with a range of i to j options

Looking to set up an ion-select menu in Ionic4 where users can pick a value between 20 and 220 without manually typing each number. I attempted to use the approach detailed in this post Tersest way to create an array of integers from 1..20 in JavaScript ...

Angular component experiencing an issue with an upgraded Angular service: encountering an Undefined error

I've been working on upgrading an AngularJS app to Angular, but I've hit a roadblock. I'm trying to configure Angular to handle the home route, but it's not working. The issue seems to stem from the upgraded service. Interestingly, whe ...

Unlock the power of asynchronous dependencies on a global scale with Inversify

I'm looking to resolve an asynchronous dependency at the top level without relying on top-level awaits. Currently, I've implemented a temporary solution by defining an asynchronous function getService() in the controller file. However, this appr ...

Dynamically passing output placeholders through ng-content in an Angular component template

Can a component handle dynamic projection in this way? <my-component [date]="2022-03-22"> <p>This particular date falls on a <strong #dayName></strong>! It is in week number <span #weekNum></span> of year &l ...

Error: Unable to locate module: Cannot find module './' in 'C:pathToFeeds'

Despite the numerous times this question has been asked before, none of the answers seem to apply to my specific situation. The issue I am encountering in my application is highlighted in the title: Below is the layout of my app's directory: https: ...

Having trouble establishing a connection with SignalR on my backend, it just doesn't seem to work properly

I am currently working on a project where I am using Vue with TypeScript and @microsoft/signalr. My goal is to create a chat feature using SignalR, and on the backend, I am utilizing C# with ASP.NET Core and docker. Here is the code snippet I have impleme ...

Intercontinental partnership bridging two separate entities

Within my application, there is a primary module: app.component.html <h1>{{globals.title}}</h1> <router-outlet></router-outlet> In app.module.ts @NgModule({ imports: [ BrowserModule, HomeModule, NotesModule, ...

What are the best ways to utilize the langular libraries such as @angular/common and @angular/core from the dependency?

In my Angular application, I have installed an angular library which contains all the necessary dependencies such as @angular/common, @angular/core, and more. I am looking to streamline my process by using a single version of angular dependencies across m ...

Encountering a problem with SVG integration in Gatsby with Typescript

In my current project, I am experimenting with using SVG in a Typescript page in Gatsby. To achieve this, I decided to utilize the Gatsby plugin called . //gatsby-config.js { resolve: "gatsby-plugin-react-svg", options: { ...

The name 'Map' cannot be located. Is it necessary to alter your target library?

After running the command tsc app.ts, an error occurs showing: Error TS2583: 'Map' is not recognized. Should the target library be changed? Consider updating the lib compiler option to es2015 or newer. I want the code to compile without any issu ...

Utilizing a third-party npm package within an Angular 2 project

I have been trying to integrate the file-system npm library into my Angular 2 project by following these steps closely: https://medium.com/@s_eschweiler/using-external-libraries-with-angular-2-87e06db8e5d1#.1dx1fkiew Despite completing the process, I am e ...

What is the role of the handleSubmit parameter in React Hook Form?

I'm encountering an issue with TypeScript in the handleSubmit function. To start off, I am accessing the handleSubmit function through the useForm hook: const {handleSubmit, control, watch, reset} = useForm() Next, I define a submit function: con ...

Create a new ASP.NET MVC project and integrate Angular 2 for a dynamic web application

I'm currently delving into the world of Angular 2 with Typescript. The primary resource I am using is QuickStart with Angular 2. From this and other examples, it has been emphasized to create a package.json file that outlines all dependencies for th ...

Avoid duplication of elements in Angular applications

Currently, I have a component that loads animated divs based on a datasource. *Note: In the example, I've used a lot of <any> because I haven't finalized the model yet. apiService.ts dataArray: Observable<Array<any>>; constru ...

Issue: Only one type can be named "Upload" within Apollo, Express, and Type-Graphql

I've encountered an issue while trying to execute a simple Mutation for uploading an image. The error I keep facing is: "Error: There can be only one type named 'Upload'." Here's the snippet of my code: import { FileUploadI, GraphQLUp ...

What advantages do binary shifts offer in enums?

What do you think about this code snippet? /** * Bitmask of states */ export const enum ViewState { FirstCheck = 1 << 0, // result is 1 ChecksEnabled = 1 << 1, // result is 2 Errored = 1 << 2, // result is 4 ...

Tips for extracting specific JSON response data from an array in TypeScript

I have an array named ReservationResponse, which represents a successful response retrieved from an API call. The code snippet below demonstrates how it is fetched: const ReservationResponse = await this.service.getReservation(this.username.value); The st ...