简体   繁体   中英

How to parse a JSON in a GET HTTP in Ionic Angular?

I'm trying to perform the following tasks within a Ionic/Cordova application. I need to perform a GET request method to download this:

{"fantaAllenatori":[{"Posizione":1,"FantaAllenatore":"Player1","Punti":"6","V":"1","P":"0","S":"0"},{"Posizione":2,"FantaAllenatore":"Player2","Punti":"5","V":"1","P":"0","S":"0"}]}

So I mapped the object in this way (rankRows.ts):

export interface RankRow {
   posizione: number;
   FantaAllenatore: String;
   Punti: String;
   V: String;
   P: String;
   S: String;
}

And this is the fanta fanta calcio.service.ts, the module that handles the connections with the ResAPI server:

   import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { EnvService } from './env.service';
import { AuthenticationService } from './authentication.service';
import { map } from 'rxjs/operators';
import { RankRow } from '../models/rankRow';

export class RankRowsResponse {
  data: RankRow[];
}

@Injectable({
  providedIn: 'root'
})
export class FantacalcioService {

  constructor(
    private http: HttpClient,
    private env: EnvService,
    private authenticationService : AuthenticationService){}


    getMatchDay(){
      return this.http.get(this.env.API_URL + 'matchday.php').toPromise()
      .then(respone =>{
        console.log(respone);
      })
    .catch(error =>{
      console.log(error);
    })
    }

    getRank(){
      var json;
      let headers = { headers: this.authenticationService.getHeadersToken(), withCredentials: true};
      return this.http.get<RankRowsResponse>(this.env.API_URL + 'classifica.json', headers).pipe(
        map(prsp => {prsp.data;
        console.log(prsp.data.length)}));
   }
}

Where am I wrong? I'm not to able to get the light of the array so I guess I'm not able to fetch the data.

You are not return from your map function:

return this.http.get<RankRowsResponse>(this.env.API_URL + 'classifica.json', headers)
    .pipe(
        map(prsp => {
        console.log(prsp.data.length);
        return prsp;
     }));

Or just use subscribe method:

return this.http.get<RankRowsResponse>(this.env.API_URL + 'classifica.json', headers)
    .subscribe( res => 
        return res;
     }));

The pipe method allows to chain observable operators, and the subscribe is to activate the observable and to listen emitted values.

Try this:

for model:

export class RankRow {
    posizione: number;
    FantaAllenatore: String;
    Punti: String;
    V: String;
    P: String;
    S: String;
}

In component:

datalist:RankRow ;

this.service.GetDataList().subscribe(result => {this.datalist= result;});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM