【问题标题】:Angular 5, HttpClient, Subscribe doesn't map properlyAngular 5、HttpClient、Subscribe 未正确映射
【发布时间】:2018-04-15 01:59:46
【问题描述】:

从 api 获取一些数据到 JSON 数组中,如:

[{"id":19,"date":{"date":"2017-09-10 10:58:40.000000","timezone_type":3,"timezone":"Europe/Paris"},"user":{"nom":"castro","prenom":"diana","mail":"diana.castro@laposte.net","telephone":"0645507509","adresse":"21 rue durand","codePostal":"31200","ville":"Quartier Borderouge","prixDeVente":"1 250 000","commentaire":""},"feature":{"type":"Terrain + Maison","tailleParcelle":"2000 à 2500m²","longueurFacade":"10 à 12m","estimationVente":"1 000 000 à 1 250 000€","isVendeur":"Non","voisinVendeur":"Ne sait pas","alreadyMeetPromoteur":"Non","howManyProposition":"Aucune","alreadyPromise":"Non","saleDelay":"1 à 2 ans"}}]

制作一个接口来处理响应:

import { QuotationInterface } from './quotationinterface';

export interface QuotationsResponse {
  results: Array<QuotationInterface>;
}

报价接口如下:

import { DateInterface } from './dateinterface';
import { UserInterface } from './userinterface';
import { FeatureInterface } from './featureinterface';

export interface QuotationInterface {

  id: number;

  date: DateInterface;

  user: UserInterface;

  feature: FeatureInterface;
}

加载数据的服务:

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/toPromise';

import { HttpClient, HttpHeaders, HttpResponse } from '@angular/common/http';

import { Constants } from './../constants/constants';
import { QuotationsResponse } from './../interfaces/quotationsresponse';

@Injectable()
export class WebapiService {

  constructor(private http: HttpClient) { }

  public getQuotations(): Observable<QuotationsResponse> {
    return this.http.get<QuotationsResponse>(Constants._WEB_API_ROOT + 
   'quotations');
  }

}

最后,一个获取数据的方法:

  public getQuotations(): Promise<QuotationCollection> {
  return new Promise((resolve) => {
    this.webApi.getQuotations().subscribe((quotations) => {
      console.log('Quotations : ' + JSON.stringify(quotations));
      this._quotations = quotations;
      console.log('Quotations : ' + typeof this._quotations);
      // Alimente la collection elle-même
      for (let quotation of this._quotations.results) {
        console.log('quotation : ' + JSON.stringify(quotation));
        this.hydrate(quotation.id, quotation);
      }
      resolve(this);
    });
  });

  }

具体类型(平均日期)如下:

import { DateInterface } from './../interfaces/dateinterface';
import { DeserializableInterface } from 
'./../interfaces/deserializableinterface';

import * as moment from 'moment';

export class Date implements DateInterface, DeserializableInterface<Date> {
  date: string;
  timezone_type?: number;
  timezone?: string;

  public getDate(): moment.Moment {
    return moment(this.date);
  }

  public deserialize(input: any): Date {
    console.log('Deserialisation : ' + JSON.stringify(input));
    Object.assign(this, input);
    return this;
  }
}

所以...当应用程序运行时:

api 被正确调用,数据被返回,但是如果我控制台“quotations”,当我期望“QuotationsResponse”时得到“Object”,内部对象(用户,日期,功能)也是对象,所以,“getDate( )" 方法未知...

我做错了什么?

谢谢

【问题讨论】:

  • 你的hydrate函数在哪里?
  • 水合物只是一种提供 Map 对象的方法:this.collection.set(id, quote)
  • &lt;QuotationsResponse&gt; 只是一个提示,它不会导致任何转换或转换。它不能,因为 TS 在运行时不存在。
  • 您无法将 JSON 对象映射到任何自定义类。如果你想这样做,你必须在设置数据时创建该类的新对象。

标签: angular deserialization observable


【解决方案1】:

无法进行类型转换作为响应,您必须这样做:

public getQuotations(): Promise<QuotationCollection> {
  return new Promise((resolve) => {
    this.webApi.getQuotations().subscribe((quotations) => {
      console.log('Quotations : ' + JSON.stringify(quotations));
      this._quotations = quotations;

      console.log('Quotations : ' + typeof this._quotations);
      // Alimente la collection elle-même
      for (let quotation of this._quotations.results) {
        // =========== HERE =============== //
        quotation.date = Object.assign(new Date(), this.quotation.date);
        console.log('quotation : ' + JSON.stringify(quotation));
        this.hydrate(quotation.id, quotation);
      }
      resolve(this);
    });
  });
}

我还建议重命名 Date 类,这样任何人都不会与 JS 的 Date 类混淆

【讨论】:

    猜你喜欢
    • 2020-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-05
    • 1970-01-01
    • 1970-01-01
    • 2018-07-05
    • 1970-01-01
    相关资源
    最近更新 更多