我使用$ resource服务从restful服务进行数据访问。 $ resource(“path”)的结果我放入了typescript域对象。问题是我以这样的形式得到json:
{
"name_surname": "john_smith",
"years_of_employment": "10"
}
我希望将其映射到此类的域对象:
class Employee {
constructor(public FullName: string, public YearsOfEmployment: number) { }
}
因此,域类和json字段中的属性名称之间存在不匹配。是否有任何angularjs模块可用于在这两者之间进行映射,以及实现这一目标的最优雅方法是什么?
答案 0 :(得分:0)
我在我的一个项目中使用它。 它将我缩短的属性映射到可读的开发属性。 也许这个片段可以帮助你。
(function (angular) {
"use strict";
angular.module("services.mapper", []).service("mapper", [function () {
var models = {
employeeModelContract: {
name_surname: "FullName",
years_of_employment: "YearsOfEmployment"
}
};
return {
map: map,
models: models
}
function map(smallObject, contract) {
var largeObject = {};
for (var smallProperty in contract) {
if (contract.hasOwnProperty(smallProperty)) {
largeObject[contract[smallProperty]] = smallObject[smallProperty];
}
}
return largeObject;
}
}]);
})(angular);
用法:
var mappedObject = mapper.map(yourJson, mapper.models.employeeModelContract);
更新1(打字稿版本):
class MapperService implements ng.IServiceProvider {
employeeModelContract:Object= {
name_surname: "FullName",
years_of_employment: "YearsOfEmployment"
};
$get() {
return this;
}
map(smallObject, contract): Object {
var mappedObject: Object = {};
Object.keys(contract).forEach(contractProperty => {
if (contract.hasOwnProperty(contractProperty)) {
mappedObject[contract[contractProperty]] = smallObject[contractProperty];
}
});
return mappedObject;
}
}
class Employee {
constructor(public FullName: string, public YearsOfEmployment: number) { }
}
class Controller implements ng.IController {
constructor(private mapper : MapperService){}
static $inject = ["MapperService"];
json: Object = {
"name_surname": "john_smith",
"years_of_employment": "10"
}
$onInit(): void {
var mapped = <Employee>this.mapper.map(this.json, this.mapper.employeeModelContract);
}
}
angular.module("mapper", []).controller("Controller",Controller).provider("MapperService", MapperService);