请求将数据转换为对象数组

时间:2017-05-16 13:34:38

标签: arrays json angular typescript rxjs

我正在执行请求并且它正确返回一个Observable,但是我想让这些返回的对象为Setor类型,我在ServiceBase中执行泛型方法,传递要返回的对象类型泛型。

Setor类:

import { UUID } from 'angular2-uuid'

export class Setor {
    descricao: string;
    id: UUID;
}

setor.component.ts:

import { element } from 'protractor';
import { Component, OnInit } from '@angular/core';

import { SetorService } from './service/setor.service';
import { Setor } from "app/retaguarda/setor/model/setor";

@Component({
  selector: 'app-setor',
  templateUrl: './setor.component.html',
  styleUrls: ['./setor.component.css']
})

export class SetorComponent implements OnInit {

  setor: Setor;

  private setores: Setor[]; // Lista de setores

  constructor(public setorService: SetorService) {
  }

  ngOnInit() {
    this.setor = new Setor();
  }

  obterTodos(form) {
    let t = this.setorService.obterSetores().subscribe(setores => this.setores = setores);
      console.log(t);
  }
}

setor.service.ts:

import { Observable } from 'rxjs/Observable';
import { BaseService } from './../../../shared/service/base/base.service';
import { Injectable } from '@angular/core';
import { Setor } from "app/retaguarda/setor/model/setor";
import { Http } from "@angular/http";

@Injectable()
export class SetorService extends BaseService {

  uriApi: string = 'setor';

  constructor(httpService: Http) {
    super(httpService);
  }

  obterSetores(): Observable<Setor[]> {
    return this.obterTodos<Setor>('setor');
  }
}

base.service.ts:

import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions, URLSearchParams } from '@angular/http';
import { Observable } from 'rxjs/Observable';

// Observable class extensions
import 'rxjs/add/observable/of';
import 'rxjs/add/observable/throw';
import 'rxjs'

// Observable operators
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/filter';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/switchMap';

@Injectable()
export class BaseService {

  serviceUrl: string = 'http://localhost:5780/api/';
  headers: Headers;
  options: RequestOptions

  constructor(private httpService: Http) {
    this.headers = new Headers({
      'Content-Type': 'application/json',
      'Accept': 'q=0.8;application/json;q=0.9'
    });
    this.options = new RequestOptions({ headers: this.headers });
  }

  private getAll<T>(url: string): Observable<T[]> {
    return this.httpService
      .get(url)
      .map(res => res.json() as T[])
      .catch(this.handleError);
  }

  protected obterTodos<T>(url: string): Observable<T[]> {
    return this.getAll(this.serviceUrl + url);
  }

  private post<T>(url: string, data: T): Observable<T> {
    let jsonContent = JSON.stringify(data);
    return this.httpService
      .post(url, jsonContent, this.options)
      .map(this.extractData)
      .catch(this.handleError);
  }

  private extractData<T>(res: Response) {
    let body = res.json() as any;
    return body || {};
  }

  private handleError(error: any) {
    let errMsg = (error.message) ? error.message :
      error.status ? `${error.status} - ${error.statusText}` : 'Server error';
    console.error(errMsg);
    return Observable.throw(errMsg);
  }
}

JSON返回:

    [
        {
        "Descricao": "teste 1",
        "Id": "4b78ade1-39a1-11e7-a8f1-a41f72fdda5d"
        },
        {
        "Descricao": "teste 2",
        "Id": "4b7cb16f-39a1-11e7-a8f1-a41f72fdda5d"
        },
        {
        "Descricao": "teste 3",
        "Id": "4b807449-39a1-11e7-a8f1-a41f72fdda5d"
        }
   ]

缺少什么,以便JSON中的返回可以为Setor类反序列化?

1 个答案:

答案 0 :(得分:1)

如果你想使用Classes ......首先你需要在你的类中添加一个构造函数,这样我们就可以映射到Setor类型的新对象。

export class Setor {
  constructor(
    public descricao: string;
    public id: UUID;
  ) {}
}

然后我们必须映射您的响应中的每个Setor,因为属性不匹配,否则我们可以使用Object.assign而不显式声明属性。

obterSetores(): Observable<Setor[]> {
  return this.obterTodos<Setor>()
    .map(res => res.map(x => new Setor(x.Descricao, x.Id)))
}

那应该是这样做的:)

<强> DEMO