javascript - 为什么 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>;
解决方案
当 TypeScript 转换成 JavaScript 时,所有的输入信息都会丢失。Typescript 在开发期间非常有用,它会告诉您是否有任何问题,但是,如果来自服务器的数据与预期格式不匹配,它只会在您尝试访问不存在的属性时报错。
因此,每当您从后端接收数据时,如果您不确定格式(或者如果发生错误时可能返回另一种类型的对象),则谨慎地对其进行验证。
推荐阅读
- sql - 仅当所有行都存在时才更新多行
- ios - 如何使用 NSPersistentCloudKitContainer 和 SwiftUI 手动获取 CloudKit 数据以更新 UI?
- android - 带有 kotlin 评级问题的 Firebase
- swift - SwiftUI如何在另一个完全完成后运行一个func
- r - 用标签列表中的部分字符串替换值 [R]
- typescript - Typescript - 如何根据可能的额外实现正确键入抽象泛型类的成员
- c - 为简单的 shell 分叉一个进程
- arrays - 按所选类型过滤列表 - 反应打字稿
- angular - 未捕获(承诺):NullInjectorError:StaticInjectorError(AppModule)[tabindex]
- spring - DynamoDB 中的 Spring 批处理元数据表