未加星标

Validate incoming data types with TypeScript and Angular2

字体大小 | |
[前端(javascript) 所属分类 前端(javascript) | 发布者 店小二04 | 时间 2018 | 作者 红领巾 ] 0人收藏点击收藏

I would like to know the recommended way to validate the data received from the server via AJAX or in child component via @input decorator in Angular2+ apps. In the app I currently work with I use interfaces for this, but they do not validate incoming data, i.e. when some property is missing, no run time errors about invalid type are issued:

// types.ts export interface IAuthItem { name: string; type: number; description: string; rule_name: string | any; data?: any; created_at: number; updated_at: number; selected?: boolean; } export interface IAuthItemFormModel { AuthItem: IAuthItem; oldAuthItem: IAuthItem; permissions: IAuthItem[]; assignments: IAuthItem[]; } // component.ts //other imports import { IAuthItemFormModel, IAuthItem } from './types.ts'; .... @Input() model: IAuthItemFormModel; ngOnInit() { this.getData(); } getData() { this.http.post('/api/admin/auth-item/form-data', this.model).subscribe((data: IAuthItemFormModel) => { this.model = Object.assign(this.model, data); console.log(this.model); }); } DISCLAIMER: this is purely an example of a possible approach, this doesn't mean that it needs to be valid or whatever, this is just the approach I've been using lately and allows elasticity, which is what I was looking for.

Now, onto the point.

Since interfaces don't exists in runtime, if you want to parse and effectively add any sort of "test" to acquire the desired data and eventually transform the data acquired, you should be using classes.

Here is a little example, simulating this response:

const json_response = { status: "done", refere: { "id": 13, "name": "John" } };

In our case, the logic I'm going to apply is having a Response Handler that takes care of the whole response, and a Referee class that handles the refere reference aswell.

Starting from the Referee:

interface IReferee { id: number, name: string } class Referee implements IReferee { public id: number; public name: string; private rawData: any; constructor(data?: any) { if (data !== null) { // Do some check here to check whether data is effectively coherent. this.id = +data.id; this.name = data.name; } } // This is the advantage of using a class. // Adding optional methods that may be useful here and there. get ID(): number { return this.id; } get LowerCaseName(): string { return this.name.toLowerCase(); } get Name(): string { return this.name; } get UpperCaseName(): string { return this.name.toUpperCase(); } }

The interface is NOT mandatory, it's just useful to be sure that you implement everything correctly in the class itself. The advantage here is that you can implement your own method if you want to (as seen above).

The response handler:

interface IMyJsonResponseHandler { status: string, refere: Referee } class MyJsonResponseHandler implements IMyJsonResponseHandler { private rawData: any; public status: string; public refere: Referee; constructor(data?: any) { if (data !== null) { this.status = data.status; this.refere = new Referee(data.refere); } } get Refere(): Referee { return this.refere; } }

And the same criteria is applied: basically, the param provided here is the json response. Every single handling is done in the constructor, if you want to add any strict check, do it there and eventually throw errors or whatever you need there. In this way, you can access pretty much everything of your json response and you can enjoy the intellisense thanks to interfaces and classes together. Of course you can simply accept that the JSON response is typeless, but if you need to do some strict checks and need such data for other calculations or simply want to have an easier understanding of what the properties are, then you must use classes and do checks there, because interfaces in typescript are nothing but a comfort for the developer in this case.

Example usage:

const json_response = { status: "done", refere: { "id": 13, "name": "John" } }; let res = new MyJsonResponseHandler(json_response); console.log(res.Refere.LowerCaseName);

Playground with this example which logs: john .

Advantage of this criteria: intellisense.

Alternatively, you can just easily implement an interface, but if you need complex data elaboration (or, more easily, if you need an inner property to be instantialized as a class instance) you must use other criteria.

Other sources you should check:

How to parse JSON string in Typescript

How do I cast a JSON object to a typescript class

本文前端(javascript)相关术语:javascript是什么意思 javascript下载 javascript权威指南 javascript基础教程 javascript 正则表达式 javascript设计模式 javascript高级程序设计 精通javascript javascript教程

分页:12
转载请注明
本文标题:Validate incoming data types with TypeScript and Angular2
本站链接:https://www.codesec.net/view/611766.html


1.凡CodeSecTeam转载的文章,均出自其它媒体或其他官网介绍,目的在于传递更多的信息,并不代表本站赞同其观点和其真实性负责;
2.转载的文章仅代表原创作者观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,本站对该文以及其中全部或者部分内容、文字的真实性、完整性、及时性,不作出任何保证或承若;
3.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。
登录后可拥有收藏文章、关注作者等权限...
技术大类 技术大类 | 前端(javascript) | 评论(0) | 阅读(11)