Declaring and accessing class variables in Angular 4

I am facing an issue with the following TypeScript model:

export class User {
  email: string;
  token: string;
  username: string;
  bio: string;
  image: string;
  constructor() {}
}

When I attempt to instantiate this model in another TypeScript file, it gives an error as shown in the screenshot below:

https://i.sstatic.net/e4Ctt.png

Can anyone help me understand why I am unable to instantiate and set all the properties of this model?

EDIT: Despite trying suggestions from other posts, I am still unable to resolve the issue! Here is a screenshot for reference:

https://i.sstatic.net/N9LkQ.png

Answer №1

Avoid using the keyword let in that specific context. Consider one of the following alternatives:

private payload = new User(); // if you want to restrict access outside the class
public payload = new User(); // if external classes need direct access

Your question was:

How can I set the properties in the model after creating an instance of it?

The ideal place for doing this in components is the ngOnInit lifecycle hook. This code is executed by Angular once your component is initialized (before the view is rendered)

export class MyComponent implements OnInit {

  private someProperty:int;

  ngOnInit(){
    this.someProperty = 7;
  }
}

If there are multiple tasks to perform, simply call your initialization functions within ngOnInit. In your example, you have a service. Since it's not a component, it cannot utilize this lifecycle hook. If you already know the property values while writing the code (as evident from your second screenshot), you can set them directly:

private payload:User = {
  email: '...',
  token: '...'
}

However, if the values are determined through a function, create an initializer function and call it from the consuming components.

@Injectable()
export class UserService {
  private isInitialized:boolean = false;
  private payload:User;

  public init(){
    // The initialize() method should only run once
    if(this.isInitialized) return;

    this.payload = new User();
    this.payload.email = '...';
    this.payload.token = this.someFunction();

    // Prevent the initialize() method from running again
    this.isInitialized = true;
  }

  private someFunction(){return 'token';}
}

In any component, it's enough to call this.userService.init() before using it.

Note 1: To have a single global instance of a service, it must be listed in the providers array of your main AppModule and not provided elsewhere.

Note 2: If initialization involves asynchronous operations, such as fetching data from a remote source, ensure to handle promises or observables and wait for resolution before utilizing the service.

Answer №2

When defining a variable, you are utilizing the let keyword. Experiment with removing it and see how that affects your code. The let keyword is typically used to declare function scope variables within a function, like so:

constructor() {
    let payload = new User();
}

If you intend to declare a variable as a class variable, you can do so in the following manner:

private payload: User = new User();

Once declared as a class variable, you can access these variables using the this keyword from anywhere inside a method of the class, for example:

this.payload.email = '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3e5b465f534e525b7e5b535f5752105d5153">[email protected]</a>';

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

Organizing JSON keys based on their values using Typescript

In the context of a main JSON structure represented below, I am interested in creating two separate JSONs based on the ID and Hobby values. x = [ {id: "1", hobby: "videogames"}, {id: "1", hobby: "chess"}, {id: "2", hobby: "chess ...

How can I transfer information from a map to a child component?

I'm attempting to transfer a variable from a parent component to a child component using React and Typescript. In my Table component (parent), I have the following map. It sets the 'data' variable as the value of the last element in the arr ...

Using the transform property with the scale function causes elements positioned in the bottom right corner to vanish

Issue specific to Google Chrome and Windows 10 I'm currently working on a flipbook that adjusts content size using transform:scale() based on the user's screen size. There is also a zoom feature that allows users to adjust the scale factor. I ha ...

Clearing transformation offset in Angular Material Drag and Drop

In my web application, I am working with a <div> element that has the CSS property position: absolute, placed inside a container with position: relative. The left and top properties of this element are linked to data X and Y in the backend component. ...

Typescript - Issue with accessing Express Response object

Having trouble using the methods of the Response object in my TypeScript method. When I try to log it, all I get is an empty object. It seems like the import is not providing the response as expected. import { Response } from 'express'; async sen ...

Ways to integrate npm dependencies into your Cordova plugin

Currently working on implementing a Cordova plugin called core-cordova found in this repository. This particular plugin has a dependency on another NPM package. The issue arises after installing the plugin in my app using: $ cordova plugin add @aerogears ...

What is the reason behind Rxjs switchMap only emitting the final value from an of() observable source?

Here are two code snippets, one using map and the other using switchMap. The functionality of map is clear: of('foo', 'bar') .pipe(map((val) => sanitizer(val))) .subscribe((val) => console.log('value:', val)); func ...

What is the connection between @types, TypeScript, and Webpack?

When using an exported type in a .ts file, it is necessary to import it: import {jQuery} from 'jQuery' Even after adding the import, intellisense may not work until npm install @types\jQuery is executed. If @types are installed, intellis ...

Navigating Angular: Uncover the Secrets of Unwrapping Json Data

I need some help with parsing Json data in Angular TypeScript. The data is structured as follows: https://i.sstatic.net/H7s8q.png When calling a REST API, I want to convert a Java class object into an array of model classes. How can this be achieved? "g ...

Ways to transfer arguments from a subclass component to its superclass

Currently in the process of upgrading from Angular 7 to Angular 12. I have multiple components that inherit from a shared base class, where constructor arguments are passed in. Main Component export abstract class PageBase implements OnDestroy{ const ...

Modify the key within an array of objects that share a common key

I have an object structured as follows: NewObjName: Object { OLDCOLUMNNAME1: "NEWCOLUMN_NAME1", OLDCOLUMNNAME2: "NEWCOLUMN_NAME2", OLDCOLUMNNAME3: "NEWCOLUMN_NAME3"} Next, there is an array containing objects in this format: ...

React modal not closing when clicking outside the modal in Bootstrap

I recently utilized a react-bootstrap modal to display notifications in my React project. While the modal functions correctly, I encountered an issue where it would not close when clicking outside of the modal. Here is the code for the modal: import Reac ...

Update the function's argument type signature if the current argument is a function with properties

Looking for input on a potential title change, but for now, here are the details of my specific use case: I'm currently developing a library that facilitates executing methods remotely and accessing properties across serialized boundaries like those ...

Display the current date in YYYY/MM/DD format using a single method in React and TypeScript

Is there a better way to retrieve YYYY/MM/DD data using just one method? I attempted the following: date = created_at // from API const sendDate = `${String((date.getMonth() + 1)).padStart(2, '0')}${String(date.getDate()).padStart(2, '0&apos ...

Switch on ngbAccordion via TypeScript File

I need to implement a function in my component.ts file that will toggle the accordion using a button. Can you help me with the script for this? This is my HTML code: <button (click)="toggleAcc()" type="button" class="btn btn-pr ...

Angular is patiently awaiting the completion of the subscription

Currently, I am in the process of developing a test application using Angular. The challenge arises when I attempt to retrieve data through a Get request and then return a value based on that data. The code snippet below outlines the scenario: public getN ...

Having trouble getting POST requests to work in Angular 8 for unknown reasons

Hey there! I'm currently experimenting with using POST requests to an API in Angular for the first time, but unfortunately it's not working as expected. I've checked out some other examples of code and everything seems fine. Here is a snipp ...

Which to Choose: Model Inheritance or Foreign Key Relationship?

I have encountered some challenges in trying to achieve my goal, and I believe there are multiple approaches that can be taken. I am working with a "Member" model, and now I want to incorporate a "Dependent" model that inherits certain fields and informati ...

When iterating through a list of strings using ngFor, I am unable to directly access or manipulate the individual items

Within my model, I have a list of strings. <span *ngFor="let item of model; let i = index"> <input #inputField type="text" [name]="name + '_' + i" [(ngModel)]="item" /> </span> The code snippet ab ...

The variable in Angular stopped working after the addition of a dependent component

Currently, I am working with Angular and have implemented two components. The first component is a navigation bar that includes a search bar. To enable the search functionality in my second component (home), I have added the following code: HTML for the n ...