Models and providers in Ionic

Hello,

I am doing an app that uses models. These models define objects that can correspond either to database or json send by a server. I have two providers, one for the connexion with server and one other for the connexion with database. I have class like this :

export class fooModel {

constructor(public Id: number, public bar: number) { }

getById(server: ServerProvider, id: number): Promise<any>  {
     server.http.post(`${server.UrlServer}/foo}`, {id: id})
    .toPromise().then(data => {
        //return serialisation
    })
}

}

My problem is, everytime I need to use getbyid, i need to pass server provider (and same for dtb provider). My application was made in Ionic 3 but I recently passed in Ionic 4, so I had to resolve some circular dependencies that was not a problem before. I decided to pass some datas in another provider than server. But it is called in every models and I now see the problem with passing same object everywhere, I have to change all the calls.

Is there a better way to make Ionic models, I mean without passing 3 providers everytime ?
I can migrate all static functions in a “foomodelprovider” but taht means that, for all on static functions of my model, i have to pass the object fooModel to the provider, that sounds strange

Thanks by advance

Why don’t you use a separate service layer for remote requests? A model class should ideally be just a nice type interface for a POJO.

1 Like

I thank to do that, but It means that all non-static functions already existing in the model will be moved to that service, and for all of them will take the object as argument. Maybe I’m wrong and this is the right way to do, but that sounds strange to me, should I do that ?

@laurineWermann Yeah, you should. Separation of API services and model classes is one of the classic examples of separation of concerns. The service sends stuff to the API and gets stuff back. Beyond maybe instantiation it shouldn’t care about anything else at all.

I created a service for all models. But I am struggling with circular dependencies : as an example, I need to get all users from a car, and the car of a certain user. Should I resolve it by moving these two functions in a “relation” service ?