问题
I have a server that have a route (/users for example) that return a list on user as json. I would like in my typeScript to convert the response json to an array of my user model.
For now i have something like this :
user.service.ts :
searchUser() : void {
return this.http.get('http://127.0.0.1:3000/users/' + this.serializeUrlParam({}))
.toPromise()
.then(response => response.json() as User[])
.catch();
}
my user.ts :
export class User {
infos: Object;
}
Where i use my service :
service.searchUser().then(userList=> {
console.dir(userList)
});
When i display the return value of the response.json()
i have this object :
{
users: [
{
Data : {
ID : 1,
Name : "foo",
....
}
},
....
]
}
And when i'm displaying the final data (which should be and Array of User), I have the exact same object.
Is there a way to make the as operator create and instance of User for each entry of the 'users' array returned by response.json()
and copy all the data (Id, name, etc) in the 'infos' field of the 'User' model ? By, like, override the as operator on my User model if it's possible ?
I would like to know if there is an other way that manually loop on each field, create an user instance push it to a 'result' array.
Thanks
回答1:
I agree with comments, you could very well use an Interface, and in fact I would very likely do it myself, even though the Angular style guide suggests to use classes: https://angular.io/guide/styleguide#interfaces
Here is a solution for your class (without constructor). What I'd do is to actually want to get rid of the Data
property from your response and end up with a class like this:
export class User {
ID: number;
Name: string;
....
}
Here's how to make the objects of the above class, where we first map the array and then we create instance of the User
class from the Data
object:
searchUser() : void {
return this.http.get('http://127.0.0.1:3000/users/' + this.serializeUrlParam({}))
.toPromise()
.then(response => response.json().users.map(user =>
Object.assign(new User(), user.Data)))
.catch();
}
Now we end up with an array with instances of the above User
class.
来源:https://stackoverflow.com/questions/45145385/angular-2-typescript-cast-json-to-object