简体   繁体   中英

Mapping the response to a variable angular 5

I am using HttpClient to call a get request that returns the response in the following format.

{
    "organizations": [
        {
            "id": 1,
            "name": "Team Red",
            "address": null,
            "sites": [
                {
                    "organization": 1,
                    "name": "Site A",
                    "address": null,
                    "lat": null,
                    "lon": null,
                    "id": 1,
                    "createdAt": "2017-10-23T11:07:11.000Z",
                    "updatedAt": "2017-10-23T11:07:11.000Z"
                },
                {
                    "organization": 1,
                    "name": "Site B",
                    "address": null,
                    "lat": null,
                    "lon": null,
                    "id": 2,
                    "createdAt": "2017-10-23T11:07:11.000Z",
                    "updatedAt": "2017-10-23T11:07:11.000Z"
                },
                {
                    "organization": 1,
                    "name": "Site C",
                    "address": null,
                    "lat": null,
                    "lon": null,
                    "id": 3,
                    "createdAt": "2017-10-23T11:07:11.000Z",
                    "updatedAt": "2017-10-23T11:07:11.000Z"
                }
            ]
        },
        {
            "id": 2,
            "name": "Team Blue",
            "address": null,
            "sites": [
                {
                    "organization": 2,
                    "name": "Site X",
                    "address": null,
                    "lat": null,
                    "lon": null,
                    "id": 4,
                    "createdAt": "2017-10-23T11:07:11.000Z",
                    "updatedAt": "2017-10-23T11:07:11.000Z"
                },
                {
                    "organization": 2,
                    "name": "Site Y",
                    "address": null,
                    "lat": null,
                    "lon": null,
                    "id": 5,
                    "createdAt": "2017-10-23T11:07:11.000Z",
                    "updatedAt": "2017-10-23T11:07:11.000Z"
                },
                {
                    "organization": 2,
                    "name": "Site Z",
                    "address": null,
                    "lat": null,
                    "lon": null,
                    "id": 6,
                    "createdAt": "2017-10-23T11:07:11.000Z",
                    "updatedAt": "2017-10-23T11:07:11.000Z"
                }
            ]
        }
    ]
}

I need to directly map the response to a organisation variable. I have attached the Service File code, as well as organisation and site file. The error I am getting is on response.json() and I have search that this function is not available. Any help will be appreciated.

import {Site} from "./Site";

export class Organization {
  id: number;
  name: string;
  address: string;
  sites: Site[];

  constructor(values: Object = {}) {
    Object.assign(this, values);
  }
}


---------


export class Site {
  organization: number;
  name: string;
  address: string;
  lat: string;
  lon: number;
  id: number;
  createdAt: string;
  updatedAt: number;
}

---- API Service ----

import {Injectable} from '@angular/core';
import {Observable} from 'rxjs/Observable';
import {HttpClient, HttpHeaders} from '@angular/common/http';
import {Organization} from "../models/Organization";
import 'rxjs/Rx';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';


const API_URL = "http://localhost:1337/api";

@Injectable()
export class ApiService {

  constructor(private http: HttpClient) {

  }

  public getOrganizationWithSites(): Observable<Organization[]> {

const headers = new HttpHeaders()
  .set("Authorization", "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MTEsIm5hbWUiOiJBdGlmIiwiaWF0IjoxNTIwMjY2NDQwLCJleHAiOjE1MjAzNTI4NDB9.GW5P7zDow4PcI9RaB3pn6KxPn929pmzPCnce6n8OCo8");
let organizations: any;
var options = {
  headers: headers
};

return this.http
      .get<Organization[]>(API_URL + '/user/organizations', options);

  }

      // private handleError(error: Response | any) {
      //   console.error('ApiService::handleError', error);
      //   return Observable.throw(error);
      // }
}



// Components Code

ngOnInit() {

    this.apiService
      .getOrganizationWithSites()
      .subscribe((data) => {
        this.organizations = data;

      });
    console.log(this.organizations);
}
import { HttpClientModule } from '@angular/common/http';

The HttpClient API was introduced in the version 4.3.0. It is an evolution of the existing HTTP API and has it's own package @angular/common/http. One of the most notable changes is that now the response object is a JSON by default, so there's no need to parse it with map method anymore .Straight away we can use like below

return http.get(API_URL + '/user/organizations', options);

Then in your component

@Component({
    selector: 'my-component',
    templateUrl: './MyComponent.component.html'
})
export class MyComponent{

    public organizations : Organization[] = [];

    constructor(private apiService: ApiService) {
        this.apiService
           .getOrganizationWithSites()
           .subscribe((data) => {
             this.organizations = data;
             console.log(this.organizations);


            });
        }
}

remove json part from response.json(); in ApiService as per HttpClient angular 5 no need to do it. HttpClient implicity do it.

For More Info Angular 5

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