Home > Blockchain >  Why do I get this error and how to display the data in my template?
Why do I get this error and how to display the data in my template?

Time:06-21

After fetching data from server with Angular, I got some errors to display it in my template:

error

With using {{todo.id}} I wanted to display the value of id.

Why do I get this error and how to display the data in my template?

service:

@Injectable({
  providedIn: 'root'
})
export class ApiService {
  constructor(private http: HttpClient) {

  }
  private URL="http://127.0.0.1:8000/api/product/"
  getApi():Observable<any>{
   
    return this.http.get (this.URL)

  }
  
} 

component:

export class AppComponent {
   
  title = 'angpr';
  todo:any;

  constructor(public api: ApiService) {

    

  }

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

}  

CodePudding user response:

Assuming that your data will always have an id property, you can use ? to check if your data is null in the template to prevent the error.

HTML (pay attention to the question mark after todo):

<div>{{todo?.id}}</div>

The question mark in short checks if your data is null or not, for more info check this answer.

So when your server responds, todo.id will be displayed in your template, and as long as todo is undefined you will see nothing in your template.

However, if there will not always be an id with your data from the server, you should implement a way to handle that as well.

I also recommend to define an interface for your data if you know the type of your data. For example:

interface ToDo {
   id: string // Or number or...
   // more properties...
}

todo: ToDo;
// ...

CodePudding user response:

You are trying to access a field of an undefined object. Check whether you have defined your object properly.

CodePudding user response:

GET USED TO SPECIFYING DATA TYPES

This happens because you do not specify data model when performing request. You probably recieve json, but without specifying data model json is just uknown object even if you specify responseType: json, it will be the same. Any property you try to access will give you the same error. You can go around this using JSON.parse(JSON.stringify(data)), or use ?.id but neither is proper solution in this case. You must implement interface that specifies model for recieved data

Another problem with your code, is that instead of performing subscribe via async pipe, you are performing a set inside subscription to a variable and then probably accessing its values in view. This is problematic because subscribe is asynchronous, meaning that view intends to render the value of this.todo before request is actually completed. This is probably why you can't see data

Try to console.log(this.todo) outside subscription and you will see that it is probably undefined

  • Related