0

My question: how do I convert a list of abstract classes back into their original classes (the classes that extend the abstract class).

I have a backend that returns a list of classes (List of UserModels) that all extends an abstract class. something like this:

public abstract class UserModel
{
...
}
public abstract class ContactModel: UserModel
{
...
}
public abstract class AdminModel: UserModel
{
...
}

In my front-end (Angular) I have the same setup. In C# I can simpely split those by saying var isAdmin = someModel is AdminModel;.

But when I get this list of users in the front-end I don't know how to convert these models from their abstract class back into the original classes.

I tried:

const isAdmin = Object.keys(AdminModel).every(key => user.hasOwnProperty(key));
const admin = user as AdminModel;

=> returned true with both models

and

const isAdmin = user instanceof AdminModel;
const admin = user as AdminModel;

=> returned false with both models

I hope this is possible. Thanks.

  • How are you transferring the instances from the backend to the frontend? – T.J. Crowder Mar 16 '21 at 15:09
  • I have a be method: [HttpGet] [Route("")] public async Task> GetUsers() and a method in angular: getUsers(): Observable { return this.getRequest(url); } – Joren Goossens Mar 16 '21 at 15:11
  • Yes, but how is the data transferred? JSON? XML? Something else? – T.J. Crowder Mar 16 '21 at 15:13
  • I'm assuming it is transferred as JSON. I'm using entity framework not sure this is configurable and where this is specified. – Joren Goossens Mar 16 '21 at 15:22
  • 1
    Since it appears that everything goes to the front end as the abstract class, you'd be better off not using inheritance but maybe adding a property that specifies the type of user. I don't think JSON and polymorphism are a great match. – insane_developer Mar 16 '21 at 15:35
  • 1
    Add a `string TypeName` property to your abstract class. It's implementation could simply be `string TypeName => this.GetType().Name;`. Use it on the front end. – Flydog57 Mar 16 '21 at 15:46
  • Thanks, added a userType property. Hoped the models could be split in the FE but this also works. – Joren Goossens Mar 16 '21 at 16:01
  • Does this answer your question? [Deserializing JSON to abstract class](https://stackoverflow.com/questions/20995865/deserializing-json-to-abstract-class) – Ali Ihsan Elmas Mar 16 '21 at 17:32
  • No, sorry this is a different problem. – Joren Goossens Mar 18 '21 at 07:13

0 Answers0