Ways to access information from an Angular model within a controller

hydrate.component.ts

    import { Component } from 'angular/core';
    import { userDataService } from 'some/different/path';

    @Component({
    selector: 'hydrate',
    templateUrl: './hydrate.component.html'
    })

    export class HydrateComponent implements OnInIt {
    ...
    ...
    userInfo: userModel;

    constructor (public userService : UserDataService) {}

    ngOnInit() {

    this.fetchUserInfo();

    }

    fetchUserInfo() {
    console.log('user data:', this.userService)

   //need to extract name and gender for certain logic
   //need to extract name and gender for certain logic

        }

user-data.service.ts

import { Injectable } from '@angular/core';
import { UserModel } from 'some/different/path';

@Injectable({
providedIn: 'root'
})

export class UserDataService{
public userData: UserModel;

constructor() {}
}

user.model.ts

export class UserModel {
gender: string;
name: string;
hasPets: boolean;
constructor(data: UserModel) {
this.name = date.name;
this.gender = data.gender;
}
} 

Console Output from hydrate component -> fetchUserInfo( console.log()) Please replace > with downward solid arrow as a json structure. I could not format it

   > userService {}
    > userData : UserModel
      name: lisa
      gender: male
      hasPets: true
      educator: false
      >hobbies: {music: Array(2), sports: Array(3)}
    >_proto_: Object

Question

When I try to access the name and gender within the readUsrInfo method, this.userService.gender currently returns undefined. How can I correctly retrieve these values? Any assistance would be greatly appreciated.

Answer №1

class ProfileInfo {
      name = 'Peggy'
      gender = 'female'
      ...
      ...
}

const user = new ProfileInfo()

console.log('User gender is:', user.gender)

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

Tips for arranging TypeScript AST nodes and generating a TypeScript file as the final result

My objective is to reorganize the code in a way that sorts the link(foo) value based on the string text: import Text from '~/text.js' export default function rule(text: Text) { // Sorting rules alphabetically } Although I have made some progr ...

How can I properly structure an if statement in React + Typescript when dealing with calling components?

I am currently attempting to showcase a component and hand over a function as a prop only when one of its state properties is true. However, I am struggling with the syntax. Here's my current setup: render = () => { return ( <ParentComponent& ...

Exploring Angular 2: The Power of HTTP Observables for Managing Asynchronous Operations. Exploring the

When working with a form that fetches data using an http observable, I encountered the need to disable the submit button while awaiting the response. Currently, I am setting the status code on each component/form to indicate running before calling the sub ...

Tips for refreshing the 'state' of an Angular Router component

I'm facing an issue with passing data between pages using Angular routing. Everything works as expected when navigating to the "next" page for the first time. However, upon returning to the home page and selecting a different item, the Router's s ...

My Nextjs project is encountering deployment issues with both Netlify and Heroku

Whenever I attempt to deploy my application on Heroku or Netlify, I encounter an ERROR related to an incorrect import path. It's perplexing because the import is accurate and functions properly locally. Log ./pages/_app.tsx:7:27 6:31:19 PM: Type err ...

There is an issue with the target entry-point "fullcalendar/angular" as it is missing some dependencies

My current project uses Ionic, but I'm encountering an error related to missing dependencies for "@fullcalendar/angular" when running ionic serve. Error: [ng] ERROR in The target entry-point "@fullcalendar/angular" has some missing dependencies ...

Encountering the "Maximum Update Depth Exceeded" error in React Typescript with hooks

I encountered this error: Uncaught Error: Maximum update depth exceeded. It seems to be related to calling setState multiple times within componentWillUpdate or componentDidUpdate. React limits nested updates to prevent infinite loops. I am unsure of what ...

Navigating to the next or previous item in an Angular2 Firebase collection based on the current key

In my photo gallery, I have the key of an item in firebase and would like to enable users to navigate to the next or previous picture by pressing buttons. In a non-Angular2 context, I might use the following code snippet to retrieve the next item: ref.ord ...

The process of transitioning to a different view through a button press

How can I switch to another view by clicking a button in Aurelia? Here is my code: <button class="btn btn-success " click.delegate="save()">New item</button> Typescript configureRouter(config: RouterConfiguration, router: ...

Typescript throws an error when attempting to return an array of strings or undefined from a function

I created a shallow differences function that compares two arrays of strings and returns either undefined (if the arrays are different lengths) or a string array containing matching characters at corresponding indexes. If the characters don't match, i ...

Accessing class functions in Angular 2 and Ionic

I'm currently using Ionic with Angular 2 to develop an app. However, I'm facing an issue with the code below as I am unable to access the function leaveGroup(group) within the Dialog promise. leaveGroupTapped(event, group) { this.dialogs.con ...

Sending a Post request without using XHR (non-AJAX) in Angular

To integrate an external service into our Angular Application, it is necessary to meet one requirement. The external service comes with its own User Interface, which means we must redirect to that service by sending a pure HTTP Post request to the specifie ...

React-router-dom TypeScript error when defining the type of the prop parameter in the loader

I'm having trouble with the params prop in the loader prop within the routes. I've defined the params in TypeScript, but I'm getting errors that I don't understand. Any help would be appreciated, thanks in advance. I tried to use the Cu ...

The combination of Object.keys() and the find function

Having trouble figuring out why I'm getting an error when attempting to use ES6 .find on the following data in order to retrieve the record with id number 3. { {id:10,title:'Dairy & Eggs'} {id:7,title:'Laundry & Household'} {id ...

HowlerJS: Unauthorized Access - Error Code 401

Working with Angular 7, I have developed an application that consumes data from an API. I have successfully implemented CRUD functionalities using an http-interceptor that adds a token to each request. However, I encountered a 401 error when integrating Ho ...

Next.js 13: Dealing with the "Objects are not valid as a React child" error while using async/await to retrieve data

Currently, I am working on a project using Next.js 13 and the new app directory structure. One of my tasks involves fetching data from an API. However, every time I attempt to do this with async/await, I encounter an error message stating: "Objects are not ...

Encountered an error while attempting to install the 'ionic-native' package

Currently, I am navigating through this particular link to integrate local notifications into my Ionic 2 application. To kickstart the process, I executed the following two commands: Username@DESKTOP-BNKQVBC MINGW64 ~/Reminder-App (platform-specific) $ n ...

The absence of typings.json in Typescript is creating an issue

As of now, I am encountering the following error during compilation: typings.json is missing In my existing packages.json, I have included the following dependency: "devDependencies": { "typescript": "^2.6.1", ... } Do you have any suggestion ...

How to link a selection choice to an option using Angular 13

Can anyone provide guidance on how to bind data with a select option in Angular? I've tried multiple approaches but haven't been successful in getting the data to display in the options. Any assistance would be greatly appreciated. Thank you in a ...

Leveraging Javascript Modules within a Typescript Vue Application

The issue at hand I've encountered a problem while attempting to integrate https://github.com/moonwave99/fretboard.js into my Vue project. My initial approach involved importing the module into a component as shown below: <template> <div&g ...