recorrer example array angular angular-template

example - ngfor order by angular 4



No se puede encontrar un objeto de soporte diferente ''[objeto Objeto]'' del tipo ''objeto''. NgFor solo admite el enlace a Iterables como Arrays (15)

Miré preguntas similares, pero ninguna de ellas me ayudó. Voy a recibir un objeto como el siguiente:

[ { "id": 1, "name": "Safa", "email": "[email protected]", "purpose": "thesis", "programme": "Software Engineering", "year": 2016, "language": "Estonian", "comments": "In need of correcting a dangling participle.", "status": "RECEIVED" }, { "id": 2, "name": "Safa", "email": "[email protected]", "purpose": "thesis", "programme": "Software Engineering", "year": 2016, "language": "Estonian", "comments": "In need of correcting a dangling participle.", "status": "RECEIVED" }, { "id": 3, "name": "Salman", "email": "[email protected]", "purpose": "thesis", "programme": "Software Engineering", "year": 2016, "language": "Estonian", "comments": "In need of correcting a dangling participle.", "status": "RECEIVED" } ]

y aquí está mi servicio http para recibirlo:

getRequest(){ return this._http.get("http://consultationwebserver.herokuapp.com/requests").map(res => res.json()); }

y finalmente, en el llamé al servicio de esta manera:

requests; constructor(private _http:requestService){} ngOnInit(){ this.requests=this._http.getRequest().subscribe(res=>this.requests=res); }

Desafortunadamente, cuando la página se carga, se queja con:

Cannot find a differ supporting object ''[object Object]'' of type ''object''. NgFor only supports binding to Iterables such as Arrays.

Entonces, ¿qué está mal con este código?


Allí no necesita usar this.requests= cuando realiza get llamada (entonces las requests tendrán una suscripción observable). Obtendrá una respuesta con success observable, por lo que establecer el valor de las requests en éxito tiene sentido (lo que ya está haciendo).

this._http.getRequest().subscribe(res=>this.requests=res);



Eliminar this.requests de

ngOnInit(){ this.requests=this._http.getRequest().subscribe(res=>this.requests=res); }

a

ngOnInit(){ this._http.getRequest().subscribe(res=>this.requests=res); }

this._http.getRequest() devuelve una suscripción, no el valor de respuesta. El valor de respuesta es asignado por la devolución de llamada pasada a subscribe(...)


En el uso de botas de primavera con Angular; asegúrese de que si crea por defecto


En su archivo JSOn, realice los cambios a continuación.

{ "data": [ { "id": 1, "name": "Safa", "email": "[email protected]", "purpose": "thesis", "programme": "Software Engineering", "year": 2016, "language": "Estonian", "comments": "In need of correcting a dangling participle.", "status": "RECEIVED" }, { "id": 2, "name": "Safa", "email": "[email protected]", "purpose": "thesis", "programme": "Software Engineering", "year": 2016, "language": "Estonian", "comments": "In need of correcting a dangling participle.", "status": "RECEIVED" }, { "id": 3, "name": "Salman", "email": "[email protected]", "purpose": "thesis", "programme": "Software Engineering", "year": 2016, "language": "Estonian", "comments": "In need of correcting a dangling participle.", "status": "RECEIVED" } ] }

Y después de eso:

this.http.get(url).map(res:Response) => res.json().data);

Los datos son en realidad el nombre de la colección tge del archivo json. Pruebe el código anterior, estoy seguro de que funcionará.


Mi solución es crear un Pipe para devolver la matriz de valores o el objeto de propiedades

import { Pipe, PipeTransform } from ''@angular/core''; @Pipe({ name: ''valueArray'', }) export class ValueArrayPipe implements PipeTransform { // El parametro object representa, los valores de las propiedades o indice transform(objects : any = []) { return Object.values(objects); } }

La plantilla Implementar

<button ion-item *ngFor="let element of element_list | valueArray" > {{ element.any_property }} </button>


Para iterar sobre un objeto que tiene un formato json como el siguiente

{ "mango": { "color": "orange", "taste": "sweet" } "lemon": { "color": "yellow", "taste": "sour" } }

  1. Asignarlo a una variable

    let rawData = { "mang":{...}, "lemon": {...} }

  2. Cree una (s) matriz (s) vacía (s) para guardar los valores (o claves)

    let dataValues = []; //For values

    let dataKeys = []; //For keys

  3. Recorra las teclas y agregue los valores (y las teclas) a las variables

    for(let key in rawData) { //Pay attention to the ''in'' dataValues.push(rawData[key]); dataKeys.push(key); }

  4. Ahora tiene una matriz de claves y valores que puede usar en * ngFor o un bucle for

    for(let d of dataValues) { console.log("Data Values",d); }

    <tr *ngFor=''let data of dataValues''> ..... </tr>


Puede declarar los libros (en la línea 2) como una matriz:

title: any = ''List of books are represted in the bookstore''; books: any = []; constructor(private service: AppService){ } ngOnInit(){ this.getBookDetails(); } getBookDetails() { this.service.getBooks().subscribe(books => { this.books = books.json(); console.log(this.books); }); }


Simplemente declara la var como una matriz en la que tienes los datos, funcionó para mí.

listingdata:Array<any> = []; this.listingdata = data.results.rows;

y repita los datos de listado en la página html


Tengo el mismo problema. Así es como solucioné el problema. primero cuando se produce el error, los datos de mi matriz provienen de DB de esta manera,

{brands: Array(5), _id: "5ae9455f7f7af749cb2d3740"}

asegúrese de que sus datos sean un ARRAY, no un OBJETO que lleve un array. solo la matriz se ve así:

(5) [{…}, {…}, {…}, {…}, {…}]

resolvió mi problema


Tuve el mismo error porque he asignado la respuesta HTTP de esta manera:

this.http.get(url).map(res => res.json);

Observe cómo accidentalmente llamé a .json como una variable y no como un método.

Cambiándolo a:

this.http.get(url).map(res => res.json());

Hizo el truco.


me he enfrentado al mismo problema

mi json inicial

{"items": [ {"id":1, "Name":"test4" }, {"id":2, "Name":"test1" } ] }

he cambiado mi json por dentro []

[{"items": [ {"id":1, "Name":"test4" }, {"id":2, "Name":"test1" } ] }]


this.requests=res aquí está intentando asignar la siguiente respuesta al objeto,

{"headers":{"normalizedNames":{},"lazyUpdate":null},"status":200,"statusText":"OK", "url":"xyz","ok":true,"type":4,"body":[{}]}

Como el formato del objeto es diferente del formato de respuesta, debe asignar res.body parte res.body de su respuesta para obtener los contenidos requeridos.


<ul> <li *ngFor = "let Data of allDataFromAws | async"> <pre> {{ Data | json}}</pre> </li> </ul>

use async para convertir allDataFromAws en Array Object ...


requests = []; this.requests[0] =this._http.getRequest().subscribe(res=>this.requests=res);

y

*ngFor="let product of requests[0]"