0

I created a file with the name of product.ts and then I added these codes to it:

export interface Product
{
    id:number;

}

component:

export class AppComponent {
   
  title = 'angpr';

  todo:Product;  

  constructor(public api: ApiService) {

  

  }

 ngOnInit() {
  this.api.getApi()
  .subscribe(    
    data => this.todo=data
  );}


}

after importing the interface and using todo:Product; in the above code, I got this error: Property 'todo' has no initializer and is not definitely assigned in the constructor.

The goal of using interface is displaying the fetched data in my template with using {{todo.id}}.

How can I display the fetched data in my template?

How can I solve this error: Property 'todo' has no initializer and is not definitely assigned in the constructor.?

dfs
  • 9
  • 3
  • Can you write the full code for that component including your import and services in your question? Let me try your error. – Myat Thiha Jun 21 '22 at 10:25

1 Answers1

1

Declare it as optional, as it can be optional.

todo?:Product;
  • That's wrong. OP should declare it with the `!` since the value is getting assigned later. – Jacopo Sciampi Jun 21 '22 at 09:26
  • I declared it with `!` and I got this error: `Cannot read properties of undefined (reading 'id')` – dfs Jun 21 '22 at 09:29
  • @JacopoSciampi that's you who are wrong. If the value is assigned LATER, it means until LATER, the value is undefined. –  Jun 21 '22 at 09:31
  • The error @dfs is writing is the exact reason why it's `?` and not `!`. –  Jun 21 '22 at 09:31
  • That's right, undefined. Not optional. more details [here](https://stackoverflow.com/questions/42273853/in-typescript-what-is-the-exclamation-mark-bang-operator-when-dereferenci) and [here](https://stackoverflow.com/questions/37632760/what-is-the-question-mark-for-in-a-typescript-parameter-name). The reason you're getting the cannot read property of undefined is because you need to put an `?` in your html: `{{todo?.id}}`. – Jacopo Sciampi Jun 21 '22 at 09:37
  • I used `?` and I got this error: `Object is possibly 'undefined'.` Then I used `{{todo?.id}}` in the template, and there is no error, but there is nothing to see as the `id` value. – dfs Jun 21 '22 at 09:39
  • @dfs then it's because either your view is not updated, or your HTTP return value is incorrect. Check both ! –  Jun 21 '22 at 09:40