首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将响应映射到变量angular 5

将响应映射到变量angular 5
EN

Stack Overflow用户
提问于 2018-03-05 22:22:20
回答 2查看 2.6K关注 0票数 1

我使用HttpClient调用一个get请求,该请求返回以下格式的响应。

代码语言:javascript
复制
{
    "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"
                }
            ]
        }
    ]
}

我需要将响应直接映射到组织变量。我已附上服务文件代码,以及组织和网站文件。我得到的错误是在response.json()上,我搜索到这个函数不可用。任何帮助都将不胜感激。

代码语言:javascript
复制
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);
}
EN

回答 2

Stack Overflow用户

发布于 2018-03-05 22:27:51

代码语言:javascript
复制
import { HttpClientModule } from '@angular/common/http';

4.3.0版中引入了HttpClient应用编程接口。它是现有HTTP API的演变,并有自己的包@angular/common/http。最值得注意的变化之一是,现在默认情况下响应对象是一个JSON,所以不再需要使用.Straight方法来解析它,我们可以像下面这样使用它。

代码语言:javascript
复制
return http.get(API_URL + '/user/organizations', options);

然后在您的组件中

代码语言:javascript
复制
@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);


            });
        }
}
票数 1
EN

Stack Overflow用户

发布于 2018-03-05 22:28:34

根据HttpClient angular 5从ApiService中的response.json();中移除json零件。不需要这样做。HttpClient隐含做到了这一点。

了解更多信息Angular 5

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49112567

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档