How to Use an Object Created from a Different Class in TypeScript

Scenario

In the development process, I am using an auth.service.ts. This service is responsible for fetching user information from the database upon login. The retrieved data is then used to create a new user object. Here is a snippet of the code:

 user: User;
 this.user = res;
 console.log(this.user);

The output of this code block looks like this:

Object account_locked: false affiliate_owner: null business_phone: "8178966767" city_address: null contract: false created_on: null dob: "1984-03-05T06:00:00.000Z" email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a9ccd1c8c4d9c5cce9ccc4c8c0c587cac6c4">[email protected]</a>" employee_owner: null fax_number: "1234567" first_name: "Nicholas" home_phone: "1234567" id: 7last_name: "theman" middle_name: "dude" mobile_phone: "1234567" ssn: "123456789" state_address: null street_address: null user_auth_level: 1 zip_address: null __proto__: Object

The issue arises when trying to access the user object in another class by importing the auth.service.ts.

import { Auth }                    from './../services/auth.service';

constructor( private router: Router, private auth: Auth, private http: Http  ) { }

However, the following line of code returns undefined:

ngOnInit() {
      console.log(this.auth.user);
     }

Similarly, attempting to utilize interpolation in the template {{auth.user.email}} does not yield the desired result.

Query

How can I efficiently access the user object generated in auth.service.ts from a different class, specifically profile.component.ts and its corresponding HTML template profile.component.html?

Could this issue potentially be related to inheritance?

Essential Code Snippets

    auth.service.ts

    export class Auth {
      lock = new Auth0Lock(myConfig.clientID, myConfig.domain, options, {});
      userProfile: Object;
      logreg: LogReg;
      user: User;
      constructor(private router: Router, private http: Http ) {
            // create users
            this.logreg = new LogReg(profile.email);   
            this.checkRegister(this.logreg).subscribe((res)=>{
                //do something with the response here
                this.user = res;
                console.log(this.user);
            });
    }
}

I aim to retrieve the user object defined above in the following context:

profile.component.ts

import { Auth }                    from './../services/auth.service';

@Component({
    providers: [ Auth ],
    templateUrl: './profile.component.html'
})
export class ProfileComponent implements OnInit {

    constructor( private router: Router, private auth: Auth, private http: Http  ) { }

    ngOnInit() {
      console.log(this.auth.user);
     }
}

Answer №1

To establish a base class model named BaseObject within the file objects.ts, you can use the following code:

import * as P from "./protocols"

export class BaseObject implements P.ObjectProtocol {

/** 
     * Fill object by properties dictionary
     * @param properties Object Properties dictionary
    */
    public fill(properties:Object) {
        var self=this;
        for (var i in properties) {
            if (self.hasOwnProperty(i)) {
                self[i]=properties[i];
            }
        }
    } 
}

To export this object, utilize export class.

When using this class elsewhere, include the following code:

import {BaseObject} from "./objects"
export class MyObjectImpl extends BaseObject {
 //...
}

If dealing with the issue of sharing the object instance, consider implementing a singleton pattern. More information can be found here: Access key data across entire app in Angular 2 & Ionic 2

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

Pressing the reset button will restore the table to its original

As a new React developer with experience mainly in hooks, I have been struggling to find a good example involving hooks. Currently, I am working on implementing an antd table with search functionality. My question is, when a user types something into the ...

React | Utilizing ForwardedRefs with React Components

I'm currently working on a React project where I am creating a custom component that needs to be exported using forwardedRef. However, as I attempt to do this, an error keeps popping up: error This is the code snippet causing the issue: export inter ...

Sophisticated web applications with Ajax functionalities and intricate layouts powered by MVC frameworks

I am looking to integrate an ajax-driven RIA frontend, utilizing JQuery layout plugin (http://layout.jquery-dev.net/demos/complex.html) or ExtJs (http://www.extjs.com/deploy/dev/examples/layout/complex.html), with... a PHP MVC backend, potentially using ...

Is the 404 page being utilized as a fallback for AJAX requests?

I am looking to create a one-page website that utilizes history.pushstate to modify the URL. My plan involves having only one HTML file for the site, which would be the 404 error page. This setup would redirect users to that page regardless of the URL they ...

What is the process for removing a record from a table using Angular's http.delete method with a PHP backend

I'm attempting to remove a record from the database table using Angular on the front end and PHP on the back end. I'm passing the id through the URL and trying to retrieve it with $_GET['id'], but it's not working (no errors in the ...

Angular 2 Introductory Guide - where to find the necessary files

I recently began diving into Angular 2 and I am in the learning process. However, I encountered an issue after running the command: npm install -g angular-cli. The problem is that I cannot locate the following folder on my hard drive: src/app / ./src/app/a ...

Improve the looping mechanism to efficiently extract key values from an object and store them in an array

I am working with an object that contains various questions, each with a different difficulty level indicated by the "difficulty" property. I have implemented a for loop to sort the questions into categories based on their relative difficulty, such as easy ...

Is there a way to retrieve two separate route details using jQuery simultaneously?

Clicking the checkbox should display the Full Name: input type="text" id="demonum" size="05"> <button type="button" onclick="load_doc()">click</button><br><br> <input type="checkbox" id ="check" > The r ...

What is the best way to send a prop for inline styling in a React component that contains an array of data?

My ShowData component is responsible for rendering in both my App.js and index.js files. import React from "react"; import SwatchData from "./SwatchData"; import { DataTestContainer } from "./DataTestContainer"; function ShowData(props) { const DataCom ...

Error: Node requires the use of 'import' to load ES modules

Here is the code snippet that I am currently working with: import { toString } from 'nlcst-to-string'; import { retext } from 'retext'; import retextPos from 'retext-pos'; import retextKeywords from 'retext-keywords' ...

AngularJS Element Connections

I have the following component: (function () { "use strict"; angular.module("application_module") .component('tab', { controller: 'TabCtrl', templateUrl: 'app/component/application/app-heade ...

Move the Div element up and down when clicked

When a tag is clicked, the corresponding div opens and closes. I would like the div to slide down and up slowly instead of appearing immediately. <a href="" class="accordion">Click here</a> <div class="panel" id="AccordionDiv"> ...

Where should AJAX-related content be placed within a hyperlink?

When needing a link to contain information for an AJAX call, where is the correct place to include the info? I have typically placed it in the rel attribute, but after reviewing the documentation for rel, it appears that this may not be the right location ...

As I go through the database, I notice that my div model functions correctly for the initial record but does not work for any subsequent ones

I came across a model on w3 schools that fits my requirements, but I am facing an issue where the model only works for the first result when looping through my database. It's likely related to the JavaScript code, but I lack experience in this area. C ...

Examining Resolver Functionality within NestJS

Today I am diving into the world of writing tests for NestJs resolvers. I have already written tests for my services, but now it's time to tackle testing resolvers. However, I realized that there is a lack of documentation on testing resolvers in the ...

Is there a way to extract data from a JSON file with dc.js?

As a beginner in programming, I am looking to learn how to import data from a JSON file using dc.js. ...

Troubleshooting Problems with Loading Data into Highcharts using Javascript

The server is returning data in the following format: {"barData": [ {"Accepted":[0,0,0]}, {"Rejected":[0,0,0]}, {"In_Process":[0,1,0]}] } On the browser, it appears as follows: I initially thought that this was the correct st ...

What steps do I need to take to create a delete button that will effectively remove a bookmark from an array?

Currently, I have created a form that allows users to input the website name and URL. Upon clicking the submit button, the output displays the website name along with two buttons: 1. one for visiting the site 2. another for removing the bookmark using on ...

How can I automatically disable certain checkboxes when a specific radio button is selected?

Looking to disable certain checkboxes when a specific radio button is selected. For instance, selecting the first radio button with the id="pz1" should disable checkboxes with matching id values from the thisToppings array. Each radio button cor ...

"Enhancing Your Web Pages: Generating and Inserting HTML Elements on the Fly Using

For my master's degree project, I am working on developing a shopping web app. The issue I am facing is that I need assistance with creating a div and adding it to the HTML file with an ID matching the category name from the .ts file when the addCate ...