2016-04-25 16 views
17

quando va a prendere JSON oggetto array api riposo e cercando di visualizzare in ngfor riuscito con la ragionevisualizzazione degli errori in * oggetto array ngfor JSON

errore

ECCEZIONE: Non riesci a trovare un differiscono di supporto oggetto '[oggetto oggetto ] 'di tipo' oggetto '. NgFor supporta solo il binding a Iterables come Array. in [indici in HomeComponent @ 5: 37]

Codice

import {Component} from 'angular2/core'; 
import {HomeService} from './home.services'; 
import {Index} from './index'; 

@Component({ 
    selector: 'home-app', 
    providers: [HomeService], 

    template: ` 
     <section class="left_side"> 
      <article> 
       <div class="div_home"> 
        <div class="div_homeIndxPartition"> 
         <div class="div_IndxPartition" *ngFor="#indObj of indexes"> 
          <table width="500px" class="idx_cons_table_det"> 
           <tr> 
            <th align="center" color="#A9F5F2"><h3>{{indObj.name}} ({{indObj.tracker}})</h3></th> 
            <th align="center">Value</th> 
            <th align="center">Change</th> 
            <th align="center">%</th> 
           </tr> 
           <tr> 
            <td align="center" colspan="1"></td> 
            <td align="center">{{indObj.value}}</td> 
            <td align="center">{{indObj.change}}</td> 
            <td align="center">{{indObj.percent}}%</td> 
           </tr> 
          </table> 
          <br/> 
          <table width="500px" class="idx_cons_table"> 
           <tr> 
            <th align="center">High</th> 
            <th align="center">Low</th> 
            <th align="center">Open</th> 
            <th align="center">Close</th> 
            <th align="center">52 Week High</th> 
            <th align="center">52 Week Low</th>        
           </tr> 
           <tr> 
            <td align="center">{{indObj.high}}</td> 
            <td align="center">{{indObj.low}}</td> 
            <td align="center">{{indObj.open}}%</td> 
            <td align="center">{{indObj.close}}</td> 
            <td align="center">{{indObj.yearHigh}}</td> 
            <td align="center">{{indObj.yearLow}}%</td> 
           </tr> 
          </table>       
         </div>      
        </div> 
       </div> 
      </article> 
     </section> 
    ` 

}) 
export class HomeComponent { 
    public indexes:Array<Index>=[]; 
    public error; 

constructor(private _service: HomeService){ 
    this.indexes = _service.getIndexes().subscribe(
      data => this.indexes = JSON.parse(data), 
      error => alert(" Error is : " + error), 
      ()=> console.log("finished") 
     ); 
    console.log(this.indexes); 
} 
} 

JSON dati

[ 
    { 
    "id": 1, 
    "name": "FTSE 100", 
    "ticker": "UKX", 
    "value": 69875.23, 
    "change": 100, 
    "percent": 2.3, 
    "high": 69875.23, 
    "low": 69700.89, 
    "yearHigh": 699999.23, 
    "yearLow": 680005.23, 
    "open": 69600.54, 
    "close": 699000.97, 
    "constituents": null, 
    "runDate": "21/04/2015" 
    }, 
    { 
    "id": 2, 
    "name": "FTSE 250", 
    "ticker": "MCX", 
    "value": 465820.85, 
    "change": 100, 
    "percent": 2.3, 
    "high": 465880.12, 
    "low": 465810.74, 
    "yearHigh": 478990.34, 
    "yearLow": 465320.23, 
    "open": 69600.54, 
    "close": 699000.97, 
    "constituents": null, 
    "runDate": "21/04/2015" 
    }, 
    { 
    "id": 3, 
    "name": "FTSE All-Share", 
    "ticker": "ASX", 
    "value": 236549.23, 
    "change": 100, 
    "percent": 2.3, 
    "high": 236949.23, 
    "low": 236149, 
    "yearHigh": 246949.21, 
    "yearLow": 235549.29, 
    "open": 236519.23, 
    "close": 236649.23, 
    "constituents": null, 
    "runDate": "21/04/2015" 
    }, 
    { 
    "id": 4, 
    "name": "Euro Stoxx 50", 
    "ticker": "STOXX50E", 
    "value": 123469.87, 
    "change": 100, 
    "percent": 2.3, 
    "high": 123499.87, 
    "low": 123439.87, 
    "yearHigh": 123499.87, 
    "yearLow": 123169.87, 
    "open": 123465.87, 
    "close": 123459.87, 
    "constituents": null, 
    "runDate": "21/04/2015" 
    }, 
    { 
    "id": 5, 
    "name": "S&P 500 ", 
    "ticker": "S500", 
    "value": 358976.36, 
    "change": 100, 
    "percent": 2.3, 
    "high": 358986.36, 
    "low": 358946.36, 
    "yearHigh": 359976.36, 
    "yearLow": 357976.36, 
    "open": 358970.36, 
    "close": 358996.36, 
    "constituents": null, 
    "runDate": "21/04/2015" 
    }, 
    { 
    "id": 6, 
    "name": "Dow Jones I.A.", 
    "ticker": "INDU", 
    "value": 456789.36, 
    "change": 100, 
    "percent": 2.3, 
    "high": 456799.36, 
    "low": 456779.36, 
    "yearHigh": 456889.36, 
    "yearLow": 456689.36, 
    "open": 456729.36, 
    "close": 456779.36, 
    "constituents": null, 
    "runDate": "21/04/2015" 
    }, 
    { 
    "id": 7, 
    "name": "GOLD", 
    "ticker": "", 
    "value": 500, 
    "change": 100, 
    "percent": 2.3, 
    "high": 700, 
    "low": 300, 
    "yearHigh": 1500, 
    "yearLow": 350, 
    "open": 450, 
    "close": 470, 
    "constituents": null, 
    "runDate": "21/04/2015" 
    }, 
    { 
    "id": 8, 
    "name": "Brent Crude", 
    "ticker": "", 
    "value": 112, 
    "change": 100, 
    "percent": 2.3, 
    "high": 115, 
    "low": 107, 
    "yearHigh": 200, 
    "yearLow": 72, 
    "open": 110, 
    "close": 115, 
    "constituents": null, 
    "runDate": "21/04/2015" 
    } 
] 
+0

Utilizzare 'data.json()' invece di analizzarlo manualmente. – Dinistro

risposta

8

penso che il valore impostato nella proprietà indexes non è una matrice, ma un oggetto .

avrei visto diverse ragioni per questo:

  • si riceve la risposta al posto del carico utile dal metodo getIndexes. In questo caso, è possibile utilizzare l'operatore map in questo metodo:

    getIndexes() { 
        return this.http.get(...).map(res => res.json()); 
    } 
    
  • Il payload ricevuto non corrisponde a un array, ma alcune delle sue proprietà. In questo caso, è necessario impostare questa proprietà nella proprietà indexes.

Se volete iterare sulle proprietà di un oggetto, è necessario implementare un filtro personalizzato come questo:

@Pipe({name: 'keyValues'}) 
export class KeysPipe implements PipeTransform { 
    transform(value, args:string[]) : any { 
    let keys = []; 
    for (let key in value) { 
     keys.push({key: key, value: value[key]); 
    } 
    return keys; 
    } 
} 

e utilizzarlo così:

<div class="div_IndxPartition" *ngFor="#indObj of indexes | keyValues"> 
    (...) 
</div> 

See questa domanda:

+0

Grazie per la risposta. Sto ottenendo array json e ho pensato che sarà convertito di nuovo all'oggetto dominio per riflessione? La mia comprensione è sbagliata? – Rafi

+0

L'utilizzo di "response.json()" analizza il payload della risposta del testo come json. L'oggetto corrispondente sarà un oggetto ... –

+0

Che cosa sono i "dati"? Come hai capito? –

0

Ho avuto lo stesso problema e la mia soluzione era senza tubi. Non ho usato la variabile nel modello che restituisce Observer, creare variabili intermedie e assegnare un risultato ad esso. Ad esempio, salveremo lo stream su this.sub ma il risultato verrà salvato in this.indexes in callback di successo e utilizzerà questa variabile nel modello html.

@Component({ 
    template: ` 
<ul> 
    <li *ngFor="let index of indexs"> 
    {{ index }} 
    </li> 
</ul> 
` 
}) 
export class HomeComponent { 
    privat sub; 
    public indexes:Array<Index>=[]; 
    public error; 

    constructor(private _service: HomeService) { 
    this.sub = this._service.getIndexes().subscribe(
     data => this.indexes = JSON.parse(data), 
     error => alert(" Error is : " + error), 
     () => console.log("finished") 
    ); 

    } 
} 
1

Si dovrebbe provare questo:

in HTML:

<div *ngFor="let subsciption of subscriptions;"> 
        <div class="col-md-6"> 
         <h5 class="widget-title">{{subsciption.name}}</h5> 
        </div> 
</div> 

nel file di .ts:

export class SubscriptionComponent implements OnInit { 
     private subscriptions: any =[]; 
     // private subscriptions: any ={}; // here dont use {} 
    . 
    . 
    . 
    . 
    . 

     getAllSubscriptions(queryString) { 
      this._http.get(`${environment.base_url}/subscriptions` + queryString) 
       .subscribe((response: Response) => { 
        this.subscriptions = response.json(); 
       }, 

       (error: Response) => { 
        console.log("Login error"); 
       }); 
     } 
     this.getAllSubscriptions(query); 

    } 
0

non si vuole usare tubi quando si lavora con Observables. Questo errore è molto generico e il modo migliore è quello di gettare in un console.log() e vedere dove stai andando male in quanto potrebbe essere numerose cose.

Il mio problema era che la mia matrice era dentro l'oggetto e stavo cercando di eseguire il loop sull'oggetto. Altri problemi potrebbero includere la mappatura o il ngFor. La mia uscita della console sarebbe simile a questa:

this.indexes = _service.getIndexes() 
     .subscribe(
      data => { 
       this.indexes = JSON.parse(data); 
       console.log(indexes); 
      }, 
      error => alert(" Error is : " + error), 
       ()=> console.log("finished") 
     ); 
    console.log(this.indexes); 

Quindi la correzione avevo bisogno era qualcosa di simile:

this.indexes = _service.getIndexes() 
      .subscribe(
       data => { 
        this.myNewObject = JSON.parse(data); 
        this.indexes = this.myNewObject.indexes; 
       }, 
       error => alert(" Error is : " + error), 
        ()=> console.log("finished") 
      ); 
     console.log(this.indexes); 

Questo perché l'array è stato annidato all'interno dell'oggetto, quindi ho solo creato un nuovo oggetto e accede all'array ottenendo la sua proprietà.