Search code examples
jsonangulartypescriptobservablehttpclient

How to Unwrap Json data in angular?


I have a Json data in this format

enter image description here

I want to parse this data in angular typescript when I am calling the rest API. How to do it.

Here this part is my java class object which I want to convert to my model class array.

"gameId": 66,
"kashScore": 0,
"samScore": 1,
"wonBy": "Sam",
"createUserId": 0,
"lastModifiedUserId": 0,
"creationDate": "2020-04-20T14:05:44.263+0000",
"lastModifiedDateTime": "2020-04-20T14:05:44.264+0000",
"sessionId": 1000,
"count": null

My model class

enter image description here

And this information is for tracking pagination.

enter image description here

I tried something like this, but it gives error as:-

enter image description here


Solution

  • Your response is just an array. The data that represents Fifa[] is the first item in the response array.

    The HttpClient won't magically convert it for you. If you want to return Fifa[] from your service, then you need to map your response to that type.

    return this.http.get<any[]>(fifaUrl).pipe(
      map((response: any[]) => response[0])
    );
    

    EDIT

    You have stated that you want to return all information from the response. In that case you should return an object that implements GetResponse from service function (and probably think about a more suitable name).

    fetchAllGamesRecordPaginate(
      pageNumber: number, pageSize: number
    ): Observable<GetResponse> { 
      const fifaUrl = ${this.baseUrl}/demo/pageNumber/${pageNumber}/pageSize/${pageSize}; 
      return this.httpClient.get(fifaUrl).pipe( 
        map((response: any[]) => {
          const pagination = response[1];
          return {
            fifa: response[0],
            totalRecord: pagination.totalRecord,
            pageSize: pagination.pageSize,
            pageNumber: pagination.pageNumber,
            totalPages: pagination.totalPages
          };
        })
      ); 
    }
    

    Here I am mapping the response array to an object that implements GetResponse.