Encountering issues with HTML loading interpolation before constructor in TypeScript

I am currently working on a project using Angular 6 and encountering some challenges.

Here is the issue at hand: I am facing an error in the HTML Console, which occurs after reloading the page. The error message indicates that the variable "atual" is undefined at the time when my HTML is loaded/created.

My question is: Why is the HTML being loaded before the constructor of my component.ts is called?

I am able to retrieve the data eventually, but I am puzzled as to what mistake I might be making. Do I need to subscribe to the event somewhere prior to the constructor?

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

This is found in my home.component.ts:

atual: Atual;
homeService: HomeService;

constructor(_homeService : HomeService) { 
this.homeService.getAtual().subscribe((res: any) => {
  console.log('Why is it called after html?');
  this.atual = res.data;
});  

The atual.ts file looks like this:

export class Atual {

  public temperature: number;
  public wind_direction: string;
  public wind_velocity: number;
  public humidity: number;
  public condition: string;
  public pressure: number;
  public icon: string;
  public sensation: number;
  public date: string;

}

This is from my home.service.ts:

getAtual(): Observable<Atual[]> {
return this.http.get('./assets/atual.json')//, options)
    .map((response: Response) =>{
      return response.json();
    } )
}

And finally, here is a snippet from my home.component.html:

<div>
  <mat-card>
    <img mat-card-lg-image src="../../assets/img/1.png">
    <mat-card-title>{{atual.date}}</mat-card-title>
  </mat-card>
</div>

Despite the error, the data is displayed after the service subscribes. It seems to go into the constructor in my component.ts eventually, but should it not do so right from the start?

https://i.sstatic.net/3w6Qi.png

Answer №1

The constructor is executed immediately, but the method getAtual operates asynchronously. As a result, the code inside subscribe is not called right away since your service needs to fetch the data first.

To prevent the error, you can utilize {{atual?.date}} instead. This employs the safe navigation operator which will only attempt to display date if atual has been defined.

Answer №2

To ensure that the variable atual is not undefined, you need to initialize it with a new instance of the Atual class.

 atual: Atual = new Atual();

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

Using the reduce method in JavaScript or TypeScript to manipulate arrays

Just exploring my culture. I have grasped the concept of the reduce principle var sumAll = function(...nums: number[]):void{ var sum = nums.reduce((a, b) => a + b , 0); document.write("sum: " + sum + "<br/>"); } sumAll(1,2,3,4,5); The r ...

Generate a <mat-error> element dynamically and ensure it is correctly projected into the parent <mat-form-field> component

Creating a component dynamically using the ComponentFactoryResolver is relatively simple, but I have encountered an issue when attempting to project the created component into its parent when working with the Angular Material <mat-error> component in ...

Troubles with Angular Form Elements: Bridging the Gap Between AbstractControl and FormControl

Encountering an error when trying to use a form with controls. Type 'AbstractControl' is missing the following properties from type 'FormControl': registerOnChange, registerOnDisabledChange, _applyFormState Check out Form Code th ...

execute a JAR file on a Windows Server

My application is running on a Windows Server using Spring Boot and Angular 2. I am looking for the best way to run the executable jar file in this environment. I have some questions regarding this setup: What is the recommended approach for running the ...

Creating a multi-level signup page in Angular 4 using Bootstrap

Currently, I am working with angular 4 and bootstrap 4 to create a multi-level sign-up page. One of the challenges I am encountering is how to properly include a JavaScript file into my angular project. import '../../../assets/js/js/multiform.js&apo ...

How can Typescript elevate your use of the IFrame API?

Here is a code snippet that performs the following actions: let doc = this.iframe.contentDocument || this.iframe.contentWindow; let content = `...` doc!.open(); doc!.write(content); doc!.close(); Despite this, the Typescript linter thr ...

After each save, gulp-typescript is emitting errors, however, it works without any issues upon subsequent saves

I'm facing some uncertainty regarding whether the issue I'm encountering is related to gulp, typescript, or Angular 2. Currently, I am using Angular 2 Beta 6. Here is an example of my typescript gulp task: var tsProject = p.typescript.createPr ...

Learn the art of bypassing TypeScript errors using @ts-ignore!

I recently encountered an issue when trying to import a pure JavaScript library into a TypeScript project, resulting in the error message: Could not find a declaration file for module xxx. After some research, I learned that this error can be suppressed u ...

Exploring Immediately Invoked Function Expressions in TypeScript

I came across an interesting article on self-invoking functions in JavaScript by Minko Gechev. This article teaches us how to create a JavaScript function that calls itself immediately after being initialized. I am curious about how we can achieve this in ...

Flow error: Unable to access the value of this.props.width as the property width is not defined in T

In my React Native project, I am utilizing Flow for type checking. For more information, visit: I currently have two files named SvgRenderer.js and Cartoon.js where: Cartoon extends SvgRenderer Below is the source code for both of these files: SvgRend ...

Struggling with TypeScript Errors while Extending Theme Colors in Material UI React using TypeScript

Just started with typescript and feeling a bit lost, can someone offer some guidance? I'm working on a React project using material-ui with typescript. To add a new color the correct way, it needs to be added to a theme: const theme = createMuiTheme({ ...

Obtain a hidden item using *ngIf in Angular for testing purposes

Snippet of HTML Code: <div *ngIf="state"> <p>some text<p> <button (click)="increment()" class="myButton">Increment</button> </div> My Component Structure: @Component( ...

Securing Your Angular 2 / ASP.NET MVC Application from CSRF Attacks

I am currently developing a single-page application using ASP.NET MVC for the backend and Angular 2 for the frontend. To prevent cross-site request forgery attacks in my application, I have implemented the following steps: Since ASP.NET MVC sends a co ...

I am attempting to update the URL of an iframe dynamically, but I am encountering an issue: the Error message stating that an Unsafe value is being

Currently, I am attempting to dynamically alter the src of an iframe using Angular 2. Here is what I have tried: HTML <iframe class="controls" width="580" height="780" src="{{controllerSrc}}" frameborder="0" allowfullscreen></iframe> COMPONE ...

Is it possible to enable autocomplete for JavaScript generated code in .proto files?

I recently created a basic .proto file with the following content: syntax = "proto3"; message Event { optional string name = 1; } After downloading and installing the protoc linux compiler (protoc-3.19.3-linux-x86_64.zip) on my local machine, ...

Is there a distinction between Entity[] and array<Entity> in TypeScript?

Everything in the title, for example people: Person[]; people: Array<Person>; What sets them apart? Is there a preferred approach? Note: I couldn't find any guidance on this and I've encountered both in code. ...

Can you identify the category of the new Set containing the elements 1, 2, and 3?

As a beginner in TypeScript, I'm currently exploring the appropriate type for JavaScript's new Set([1, 2, 3]), but my search has been unsuccessful so far. For instance: const objNums: {[key: string]: number} = {one: 1, two: 2, three: 3}; const a ...

What strategies can be implemented to avoid re-rendering in Angular 6 when the window is resized or loses focus?

I am currently working with a component in Angular 6.0.8 that consists of only an iframe element. Here is the code in page.component.html: <iframe [src]="url"> The logic for setting the URL is handled in page.component.ts: ngOnInit() { this.u ...

Angular2 Eclipse: Eclipse Oxygen's HTML editor detects TypeScript errors in real-time

After installing the Eclipse Oxygen plugin for Angular2, I created a project using the Angular CLI and opened it in Eclipse. However, when trying to convert the project to an Angular project, I couldn't find the option under configuration. Instead, th ...

Mapping an array in Typescript using Angular to instantiate a class

I have received data from a web API that resembles the structure below. I am looking for guidance on how to properly map the product array into individual Products. My main objective is to convert the eating_time values into JavaScript datetime format. Cu ...