我有一个接口INavigation,其字段名称与JSON数据中的字段不同。如何将字段从接口映射到JSON数据?
代码如下:
INavigation.ts
export interface INavigation {
Id: number;
AppId: number;
NavId: number;
Name: string;
ParentId: string;
PageURL: string;
Position: string;
Active: string;
Desktop: string;
Tablet: string;
Phone: string;
RoleId: string;
Target: string;
}
JSON数据:
{
"Id": 1,
"NavAppId": 1,
"NavId": "1FGP",
"NavName": "Home",
"NavParentId": "",
"NavPageURL": "?p=home",
"NavPosition": "Top",
"NavActive": "Y",
"NavDesktop" : "Y",
"NavTablet" : "N",
"NavPhone": "Y",
"NavRoleId" : "6,17,28,43,44,49,50,59,60,63,64,77,78,79,80,81",
"NavTarget": "_parent"
}
这是服务中从JSON文件获取数据的方法:
getNavigations(appId: any): Observable<Array<INavigation>> {
return this.httpClient.get<Array<INavigation>>('../assets/navigations.json')
.pipe(
map(data => data.filter(navigation => navigation.NavAppId === appId))
);
}
答案 0 :(得分:0)
如何在INavigation界面中更改属性?使用与JSON数据相同的名称。 以下是我的示例(角度): 我的postService代码:
pos:po[];
constructor(private postsService:PostsService) {
// get object from url.
this.postsService.getPosts().subscribe(posts=>{
console.log(posts);
this.pos=posts;
})
}
interface po{
id:number;
title:string;
body:string;
}
在我的component.ts文件中,导入服务,然后:
file-path.xml
我从url中获取的JSON数据与po接口具有相同的属性。我认为这就是您的代码无法正常工作的原因。
答案 1 :(得分:0)
此stackblitz应该给您您想要的东西。
映射操作如下:
map((data: any[]) => {
return data.map((navigation: any) => {
return <INavigation> {
Id: navigation.Id,
AppId: navigation.NavAppId,
NavId: navigation.NavId,
Name: navigation.NavName,
ParentId: navigation.NavParentId,
PageURL: navigation.NavPageURL,
Position: navigation.NavPosition,
Active: navigation.NavActive,
Desktop: navigation.NavDesktop,
Tablet: navigation.NavTablet,
Phone: navigation.NavPhone,
RoleId: navigation.NavRoleId,
Target: navigation.NavTarget
}
})
})
此外,您可能想使用实现接口的类,该接口在构造函数中接受JSON对象并在那里进行映射。这将使重用变得容易。您可以在此替代方法stackblitz
中了解如何做到这一点您当然可以完全跳过使用界面,而只使用类。