【问题标题】:Angular4 migrate from Http to HttpClientAngular4 从 Http 迁移到 HttpClient
【发布时间】:2017-09-07 02:05:37
【问题描述】:

我正在迁移我的 Angular 应用程序以使用新的 HttpClient,但我遇到了一些问题,以实现与 Http 相同的结果。希望大家帮帮我。

这就是我对 Http 所做的:

getAll() {
    return this.http.get(environment.API_DOMAIN + environment.CURRENCY_API_URL).map(res => {
        let response: ICurrenciesResponse = <ICurrenciesResponse> res.json();

        response.result = <Currency[]> res.json().result.map(service => {
            return new Currency(<ICurrency> service);
        });

    return response;
    });
}

使用 ICurrenciesResponse 接口输入响应,看起来像这样:

import { IGenericResponse } from '../igeneric-response';
import { Currency } from '../../classes/currency';
export interface ICurrenciesResponse extends IGenericResponse {
    result?: Currency[]
}

如您所见,该接口扩展了 IGenericResponse 并由 Currency 数组组成,它是一个已定义的类。为了正确设置这个数组,我必须在第二张地图上创建一个新的 Currency 对象。这非常有效,到目前为止我对这种方法非常满意。

知道,当我迁移到 HttpClient 时,我有这个:

getAll(): Promise<ICurrenciesResponse> {
    return this.http
        .get<ICurrenciesResponse>(environment.API_DOMAIN + environment.CURRENCY_API_URL)
        .toPromise();
}

但是知道我的 Currency 数组没有正确设置为 Currency 数组。 HttpClient 不是应该根据定义为 get 方法上的类型的接口来转换数据吗? 如果没有,实现与 Http 相同的最佳方法是什么?使用 subscribe() 而不是 toPromisse() 并以我已经在做的相同方式处理数据?

提前致谢!

【问题讨论】:

  • 您应该删除 angularjs 标记 - 这个问题仅与 Angular 4.x 而不是 1.x 相关

标签: angular typescript angular4-httpclient


【解决方案1】:

HttpClient 试图为响应找到正确的内容类型,它不会根据响应中的数据为您创建实例。

您仍然必须使用map 运算符并在其中创建实例。但是您必须删除.json() 调用。

getAll() {
    let url = environment.API_DOMAIN + environment.CURRENCY_API_URL;
    return this.http
        .get<ICurrenciesResponse>(url)
        .map(response => {
            if(Array.isArray(response.result) {
              response.result = response.result.map(service => new Currency(service));
            }
            return response;
        });
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-27
    • 1970-01-01
    • 2016-05-25
    • 2016-09-24
    • 1970-01-01
    相关资源
    最近更新 更多