首页 > 解决方案 > 为什么 TypeScript 不能正确传递对象实例?

问题描述

我一直致力于为 Angular Web 应用程序实现功能。我们连接到各种 API 端点,这些端点返回 JSON 响应。以下是此类请求的示例:

import { RecipesResponse } from '../../models/response/recipes';

getRecipes(): Observable<RecipesResponse> {
    const url = `/recipes`;

    return this.http.request('GET', url).pipe(
    catchError(this.errorHandler.handleError)
    ) as Observable<RecipesResponse>;
}

Observable 'Recipes Response' 对象类定义如下:

export class RecipesResponse {
    errors: string[];
    recipes: string[];

    constructor(args: any) {
        if (!args) {
            return null;
        }

        for (const field in args) {
            if (args.hasOwnProperty(field)) {
                this[field] = args[field];
            }
        }
    }
}

这是来自 Angular 组件的请求逻辑:

getTheRecipes(): void {
    this.recipeService.getRecipes().pipe(
        takeUntil(this.unsubscribe)
    ).subscribe(
        response => {
            const recipesResponse = new RecipesResponse(response);
        },
        error => {
            console.log(error);
        }
    );
}

这里的区别在于response服务器如何提供数据,并recipesResponse根据RecipesResponse类格式化数据。但是,我希望response根据返回的RecipesResponse类进行格式化。为什么它不能以这种方式工作?getRecipes()as Observable<RecipesResponse>;

标签: javascriptangulartypescriptobservable

解决方案


当 TypeScript 转换成 JavaScript 时,所有的输入信息都会丢失。Typescript 在开发期间非常有用,它会告诉您是否有任何问题,但是,如果来自服务器的数据与预期格式不匹配,它只会在您尝试访问不存在的属性时报错。

因此,每当您从后端接收数据时,如果您不确定格式(或者如果发生错误时可能返回另一种类型的对象),则谨慎地对其进行验证。


推荐阅读