Creating Instances of Variables Within a Class

Currently, I am working on a project using Ionic and Angular. I have come across various ways of instantiating variables and I'm unsure about the implications of each method. Here are three scenarios that confuse me:

export class someClass {
  myVariable: string
  ...

  someFunction() {
     // How does this method of instantiation work?
     this.myVariable = 'foo';
  }
}

Does this just create a default string object that gets overwritten with "foo"?

export class someClass {
  appService: AppService
  constructor(appService: AppService) {
     // How is this different from excluding it from the constructor?
     this.appService = appService;
  }
}

What does setting `this.appService` like this mean? Does it create duplicate instances?

export class someClass {
  constructor(private storage: Storage) {}
  
  async getSomeVariable(): Promise<any> {
     // The parameter is mentioned in the constructor but not defined outside of it?
     return await this.storage.get('someVariable');
  }
}

Is a default instance of "Storage" created when done this way for later access in the function?

Answer №1

Let's dive into your initial example:

export class someClass {
  myVariable: string
  ...

  someFunction() {
     // Able to access without instantiation.
     this.myVariable = 'foo';
  }
}

someClass contains a property called myVariable, eagerly awaiting to hold a value. Currently, it remains undefined. Within someFunction(), it fulfills its purpose and stores the value foo. Its journey is complete. This concept of class-level properties is standard in many languages, such as C#:

public class SomeClass {
  private string _myVariable;

  public void SomeFunction() {
    _myVariable = "foo";
  }
}

Moving on to your second example:

export class someClass {
  appService: AppService
  constructor(appService: AppService) {
     // Redundant code when Angular handles injection efficiently.
     this.appService = appService;
  }
}

This redundancy can be simplified by utilizing Angular's dependency injection approach:

constructor(private readonly appService: AppService) { }

No need for additional settings since Angular manages the injection seamlessly.

Lastly, let's explore your third example:

export class someClass {
  constructor(private storage: Storage) {}
  
  async getSomeVariable(): Promise<any> {
     // Parameter mentioned in the constructor but no further definition or assignment.
     return await this.storage.get('someVariable');
  }
}

Similar to the previous example, Angular simplifies the process through dependency injection and automates the storage variable management.

In conclusion, while the concepts may seem complex at first glance, understanding Angular's implementation will clarify the processes involved.

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

Sign out of Google and Facebook accounts using Angular framework

Upon logging in to both Facebook and Google using this package, I am facing an issue with signing out. Even after using the code provided below, I cannot seem to sign out of Google and Facebook: this.authService.signOut(); sessionStorage.clear(); Any as ...

displaying an AngularJS ng-repeat as empty following the completion of an Ionic loading operation

When using $ionicLoading to load the news page, a message is displayed if no news is found: <div ng-show="!news.length" class="empty"> Nothing to show ! </div> However, there is an issue where the empty div (Nothing to show !) is visible durin ...

Transforming a material-ui component from a class to a function

Currently, I am in the process of learning material-ui, and it seems that most of the code examples I come across are based on classes. However, the new trend is moving towards using functions instead of classes due to the introduction of hooks. I have be ...

`Why am I unable to achieve the proper body shape with Angular?`

When using Angular to retrieve registration information from an HTML form and then posting it to an API path, everything seems to be working fine. However, the word "work" is being printed and I am unable to get the value in the body. I have tested the POS ...

What is the best way to include a new property to an existing interface and then export the updated interface in Typescript?

Can you provide guidance on creating a new interface - UIInterface that combines SummaryInterface with additional properties? For example: import { SummaryInterface } from 'x-api'; // summaryInterface includes 20+ predefined properties generated ...

Encountering ExpressionChangedAfterItHasBeenCheckedError during ngOnInit when utilizing Promise

I have a simple goal that I am working on: I want to display data obtained from a service in my component. This is how it used to work: In my component: ... dataSet: String[]; ngOnInit(){ this._service.getDataId().then(data => this.dataSet = da ...

Send a function as a parameter to another component, but it remains dormant

I am attempting to control the enable and disable state of a button based on changes in a value. To achieve this, I have defined a model as follows: export class Model{ label:string=''; isEnabled:Function=()=>true; } The component1 i ...

Issue: Unrecognized element type in next.js while starting development server

Every time I run npm run dev, I encounter the following error: Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from th ...

Utilizing Angular and Python for VNC console

Is there a method to link an angular 7 application to a Windows or Linux machine VNC using Python on the backend that you are aware of? We are hoping to create a section in our angular 7 application where we can input VNC details and then access the remot ...

Is there a convenient method for setting up and activating real-time TypeScript checking in Windows 10 using VS Code?

After successfully installing VS Code on my Windows 10 system, I decided to follow the instructions provided here. Upon completion, Node and NPM were also installed correctly. However, I noticed a gap in the setup instructions between installing TypeScrip ...

Tips for customizing the appearance of Ionic's navigation bar

I attempted to customize the background-color of an ion-nav-bar by using the following code: <ion-nav-bar class="backarrow-bar" ng-style="{'background-color': rgba(255, 0, 0, 0.5)}" style="background-color:rgba(255, 0, 0, 0.5)"> <io ...

Empty nested Map in POST request

I am currently working on a springboot application with a React/Typescript frontend. I have defined two interfaces and created an object based on these interfaces. export interface Order { customer_id: number; date: Date; total: number; sp ...

Ways to retrieve and upload a blob from a file object

After receiving a file object via an HTML input on-change event in my component.html: onFileSelected(event) { this.selectedFile = event.target.files[0]; } Now, I need to send a POST request to upload the image to the database. The database only acc ...

Access your Angular 2 application on an external device during the development process

Is there a way to view your app in an external device like a cell phone web browser, instead of just running npm start and viewing it in your desktop browser? ...

Set up a global variable for debugging

Looking to include and utilize the function below for debugging purposes: export function debug(string) { if(debugMode) { console.log(`DEBUG: ${string}`) } } However, I am unsure how to create a globally accessible variable like debugMode. Can this be ...

Error encountered during installation of Nativescript Post Install Script

While I am comfortable running one of our current projects with Nativescript, I encountered an error when attempting to install it on a new project using the following command: sudo ng new --collection=@nativescript/schematics the-juice-box --shared The ...

Understanding the limitations of function overloading in Typescript

Many inquiries revolve around the workings of function overloading in Typescript, such as this discussion on Stack Overflow. However, one question that seems to be missing is 'why does it operate in this particular manner?' The current implementa ...

Creating dynamically generated routes in Angular or Angular 9 before initialization

I'm currently working on a project where I am in the process of converting an AngularJS application to Angular. The main challenge that I am facing at the moment revolves around routing. To sum it up: My requirement is to define routes based on an AP ...

Using an Object as a Key in Maps in Typescript

I had the intention of creating a Map object in Typescript where an object serves as the key and a number is the value. I attempted to define the map object in the following manner: myMap: Map<MyObj,number>; myObj: MyObj; However, when I tried to a ...

Utilizing custom routing rules to fetch data from a local JSON file using http.get in Angular 2

Currently facing a challenge with Angular as a beginner, specifically when attempting to retrieve a local .json file using http.get. The issue seems to be related to my routing configuration, and I'm unsure how to resolve it. File Structure: api ...