简体   繁体   English

将响应映射到可变角度5

[英]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. 我正在使用HttpClient调用get请求,该请求以以下格式返回响应。

{
    "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. 我收到的错误是在response.json()上,并且我搜索到此功能不可用。 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. 在4.3.0版中引入了HttpClient API。 It is an evolution of the existing HTTP API and has it's own package @angular/common/http. 它是现有HTTP API的发展,并具有自己的软件包@ 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 最值得注意的变化之一是现在响应对象默认为JSON,因此不再需要使用map方法进行解析。直接我们可以像下面这样使用

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(); response.json();删除json部分response.json(); in ApiService as per HttpClient angular 5 no need to do it. 在HttpClient angular 5中的ApiService中不需要这样做。 HttpClient implicity do it. HttpClient隐式地执行此操作。

For More Info Angular 5 有关更多信息Angular 5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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