Read Json Angular 9 format

Asked

Viewed 262 times

-3

my api returns a json format as follows

{
  "Errors": [],
  "Result": [
    {
      "CompanyName": "teste inicio",
      "FantasyName": "inicio"
    },
    {
      "CompanyName": "teste meio",
      "FantasyName": "meio"
    },
    {
      "CompanyName": "teste final",
      "FantasyName": "fim"
    }
  ],
  "Message": "Solicitação atendida com sucesso!"
}

so far quiet, using Angular 9 my service that makes consumption in my API

 read(): Observable<Restaurant[]>{
 return this.http.get<Restaurant[]>(this.baseUrl);

my component.ts file where you query in my service

ngOnInit(): void {
this.restaurantService.read().subscribe(restaurants => {
  this.restaurants = restaurants
  console.log(restaurants)
})

in the browser console it quietly displays the return of the API as already exemplified at the beginning, when I will display on screen the data returned in "Result:" or show the value in "Message", resumes the following message

error TS2339: Property 'Result' does not exist on type 'Restaurant[]'

Follow the HTML code

<ul>
<li *ngFor="let item of restaurants">
    {{ item.restaurants }}
</li>
</ul>

Either by putting the "Result" in . html or compote . ts the error is the same.

  • Yes, it will be a mistake! At the time the Html is rendered the return of the Api may not have been solved yet (because it is accessing data from an api the return is asynchronous) so the error.

  • Any hint of how to solve, despite the error shown it ends up showing on screen the data when I put the "Result" directly in ngFor

  • Could post variable declaration Restaurants?

  • Yes, Restaurants: Restaurant[]

  • I removed the answer, because I thought it was a problem, but apparently there must be another problem, and since I can not test I do not know how to help.

1 answer

1


This message is why the 'Result' on Restaurants. Try to make this way:

ngOnInit(): void {
    this.restaurantService.read().subscribe((restaurants:any) => {
         this.restaurants = restaurants.Result
    })
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.