Instance of an Angular TypeScript class

I have a TypeScript class named User with various properties such as id, userName, age, and more. The class also includes a fullName method that combines the givenname and surname of the user. Additionally, there is a sayHello function that logs a greeting message.


 export class User {

    id: number;
    userName: string;
    knownAs: string;
    age: number;
    gender: string;
    created: Date;
    lastActive: Date;
    photoUrl: string;
    city: string;
    country: string;
    surname: string;
    givenname: string;

    get fullName(): string {
        return `${this.givenname} ${this.surname}`;
    }

    sayHello() {
        console.log(`Hello, my name is ${this.surname} ${this.givenname}!`);
      }
}

Next, I have a service function:



    user: User;
    this.userService.getUser(this.loggedUser.nameid).subscribe((user: User) => {
        this.user = user;
        this.user.givenname = this.loggedUser.given_name;
        this.user.surname = this.loggedUser.family_name;
        console.log(this.user.fullName);
        this.user.sayHello();
      });

However, when checking the console for the results, I encountered an issue where console.log(this.user.fullName) returned 'undefined' and this.user.sayHello() threw an error 'TypeError: Object doesn't support property or method 'sayHello'. How can I access the properties and functions defined within the User class once I retrieve the data from the server?

Answer №1

To enhance the functionality of the User object received from the service, consider creating a separate prototype object specifically for User. The original User object may not have access to all the necessary functions.

user: User;
this.userService.getUser(this.loggedUser.nameid).subscribe((user: User) => {
    this.user = Object.assign(new User, user) //-->take note of using new here..
    this.user.givenname = this.loggedUser.given_name;
    this.user.surname = this.loggedUser.family_name;
    console.log(this.user.fullName);
    this.user.sayHello();
  });

Note: According to MDN, JavaScript classes serve as more of syntactical sugar rather than introducing a completely new object-oriented inheritance model in ECMAScript 2015.

JavaScript classes, introduced in ECMAScript 2015, are primarily syntactical sugar over JavaScript's existing prototype-based inheritance. The class syntax does not introduce a new object-oriented inheritance model to JavaScript.

Learn more about JavaScript classes here

Also, as mentioned by @theMayer in the comment section, the service responsible for providing the user object could return a properly structured User object with all the required prototype functions. This transfer of responsibility from the client to the service allows for better code reusability and cleaner implementation.

Therefore, in the UserService.ts file (or wherever the userService is defined), you can do something like:

getUser(id: string):User {
  //existing logic
  return Object.assign(new User(), user)//--> different methods exist to create objects, this is just one approach.
}

Answer №2

You haven't initialized an instance of User.
Below is a sample implementation :

 export class User {

    id?: number;
    userName?: string;
    knownAs?: string;
    age?: number;
    gender?: string;
    created?: Date;
    lastActive?: Date;
    photoUrl?: string;
    city?: string;
    country?: string;
    surname?: string;
    givenname?: string;

    constructor(args: User = {}) {
      this.id = args.id;
      this.userName = args.userName;
      this.knownAs = args.knownAs;
      this.age = args.age;
      this.gender = args.gender;
      this.created = args.created;
      this.lastActive = args.lastActive;
      this.photoUrl = args.photoUrl;
      this.city = args.city;
      this.country = args.country;
      this.surname = args.surname;
      this.givenname = args.givenname;
    }

    get fullName(): string {
        return `${this.givenname} ${this.surname}`;
    }

    sayHello() {
        console.log(`Hello, my name is ${this.surname} ${this.givenname}!`);
      }
}

Utilize map to instantiate your User object :

user: User;
this.userService.getUser(this.loggedUser.nameid)
  .pipe(map((user: User) => new User(user)))
  .subscribe((user: User) => {
    this.user = user;
    this.user.givenname = this.loggedUser.given_name;
    this.user.surname = this.loggedUser.family_name;
    console.log(this.user.fullName);
    this.user.sayHello();
  });

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

When attempting to display the title of a route in an Angular header component, it consistently results in undefined

I am facing a seemingly simple issue. I have a header component that needs to display the title of the currently active route. To achieve this, I am injecting the ActivatedRoute into the header component and attempting to display the route title using the ...

The Angular data table is encountering an issue as the dataStream.pipe function is not recognized

I'm currently working on setting up a table using Angular data table, but I've run into an issue related to the dataSource. I'm seeing an error message that says "dataStream.pipe is not a function", and I'm having trouble resolving it. ...

JavaScript's blank identifier

One interesting feature in Golang is the use of the _ (Blank Identifier). myValue, _, _ := myFunction() This allows you to ignore the 2nd and 3rd return values of a function. Can this same concept be applied in JavaScript? function myFunction() { re ...

Combining and consolidating data from state using Angular with ngrx

I've been struggling to come up with a way to create a grouped and summarized array of values (to be used with ngFor) from a list of objects, but I just can't seem to get it right. The data, which is a subset of my state, is structured like this: ...

What is the proper way to assign a class name to an animation state in Angular 2/4?

I am currently working with Angular Animations using version 4.1.3 Check out the code snippet below: @Component({ selector : 'my-fader', animations: [ trigger('visibilityChanged', [ state('true' , style({ opaci ...

Retrieve information from an XML document

I have some XML content that looks like this: <Artificial name="Artifical name"> <Machine> <MachineEnvironment uri="environment" /> </Machine> <Mobile>taken phone, test when r1 100m ...

Enabling withCredentials in Angular 6 for every HttpClient request is crucial for maintaining consistent authentication and

Is there a method to set { withCredentials: true } as the default for every httpclient call, instead of having to add it manually each time? import { HttpClient } from '@angular/common/http'; ... constructor(private httpclient: HttpClient) { } ...

The issue encountered is: "Uncaught promise error: Provider for ActivatedRoute not found."

The dependencies listed in the package.json file are: "dependencies": { "@angular/cli": "1.0.0", "@angular/compiler-cli": "^4.0.0", "@angular/common": "^4.0.0", "@angular/compiler": "^4.0.0", "@angular/core": "^4.0.0", "@angular/forms": "^4.0.0", "@angula ...

Event for closing Angular Material date picker

Using the Angular Material date picker as shown below. After closing the date picker, I would like to apply some CSS. Please note that there is no button to close the popup. Here is the code: <input matInput #resultPickerModel="ngM ...

Display and unveil Bootstrap modals

In my Angular5 web application, I am looking to switch from one modal to another while utilizing bootstrap components and Jquery. $('#myModal').modal('show'); $('#myModal1').modal('hide'); However, I have encounter ...

Inversify's Http Context consistently remains void of any content

Hello there, I'm in need of assistance with building an API using inversify and inversify-express-utils. Everything seems to be working fine with my controllers and the API so far, except for one issue. When trying to access the httpContext property i ...

How can I properly configure the 'main' file in angular-cli.json to utilize Express?

While attempting to set up an express server using Angular 2, I noticed in various configuration examples that the angular-cli.json file was being modified to point to a server.js file as the main configuration. However, after making this change, the appl ...

How can I effectively link data to an Angular Material dropdown in Angular 5?

Essentially, I am updating a user profile with user information that needs to be bound to the corresponding fields. this.editOfferprice= new FormGroup({ xyz : new FormControl(xxxx,[]), xxx: new FormControl(xxxx,[Validators.required]), ...

Secure higher order React component above class components and stateless functional components

I have been working on creating a higher order component to verify the authentication status of a user. Currently, I am using React 15.5.4 and @types/react 15.0.21, and below is a simplified version of my code: import * as React from 'react'; i ...

Unable to verify Angular 5 identity

After authentication, the application should redirect to another page. However, despite successful authentication according to the logs, the redirection does not occur. What could be causing this issue? auth.guard.ts: import { Injectable } from &apos ...

Angular 7 routing glitches causing page refresh issues

Here is the issue I'm facing: I am looking for a way to switch between tabs in my navigation bar without having to refresh the entire website. I have just started working with Angular and I believe that the router should be able to route to a new pag ...

Function input custom operator in RxJs

I am currently working on developing a custom rxjs operator. My previous custom operators, such as MonoTypeOperatorFunction or the regular Observable that accepts input like strings or numbers, have been successful. However, I am facing a challenge with cr ...

Failure of ngClass in Angular 7 due to the presence of multiple classes (spaces)

Many frontend frameworks have a practice of encapsulating their CSS styling by adding another class as a prefix. For example, in Bootstrap: btn btn-primary where btn is the prefix. If I were to conditionally apply this using [ngClass] in Angular, it woul ...

Discover the step-by-step process for populating hierarchical data with ngFor in Angular 2

I need help populating a table using Angular 2 that contains hierarchical data. Here is the code I am currently using: <tr *ngFor="let branch of branches"> <td (click)="onExpandClick(branch)" contenteditable="true">{{branch.name}}</td&g ...

Within an Angular test scenario, execute a static method from a service that triggers an HTTP get request to fetch stored JSON data. This data is then retrieved and returned back to the service

Currently, I am facing a challenge in my Angular test case where I am trying to load JSON data via an HTTP call. The issue arises when a static method is called from a service spec file named "url-service.spec" to another service named "load-json.service. ...