Data returning from api call through service to component is an object and seems to need to be an Array for Angular

前端 未结 2 796
死守一世寂寞
死守一世寂寞 2021-01-07 11:22

I have data returned to me that works just fine

working data is

data: Array(16)

Data that is NOT working is like this

相关标签:
2条回答
  • 2021-01-07 11:51

    I think you need to set testing = result.data, and iterate through that.

    this.arsSevice.getMenu()
            .subscribe(
                result => {
                    this.testing = result.data; 
    
                })
    

    this will give you access to the array in 'data'

    I tried to change the shape of the data, and this worked for me. Hopefully it works for you...

    var data={
          menu1Items:[{key:"boo", key2:"hoo"}],
          menu2Items:[{key:"boo2", key2:"hoo2"}]
        }
        var tempData:any[]=[];
        for(var key in data){
          if(data.hasOwnProperty(key)){
            tempData.push(data[key]);
          }
        }
        this.data = tempData;
    }
    

    In your template:

    <ul *ngFor="let menu of data ">
      <li>
          <ng-container *ngFor="let menuItem of menu">
              {{menuItem.key}} / {{ menuItem.key2}}       
          </ng-container>
      </li>
    </ul>
    
    0 讨论(0)
  • 2021-01-07 12:00

    With HttpClient angular automatically parses the reponse into an object. It doesn't know what type of object that is, so it's just a normal object that doesn't know its array properties.

    That's because while HttpClient parsed the JSON response into an Object, it doesn't know what shape that object is.

    But you can tell angular what type the returning object is so it is cast properly. For example if you get back an array of strings you could do something like this.

    return this.http.get<string[]>(apiUrl)
    

    You can read more here, they are describing a similar problem, just with a little different structure.

    0 讨论(0)
提交回复
热议问题