I've been going back and forth this whole weekend of how I'm supposed to think when structuring models and classes for my project and I just can't wrap my brain around it.
I'm gonna try and explain as best as I can (and please comment if I should explain further), I have a remote api where I pick up some lists that are going to be displayed in an app. The response from the API is in JSON and I get my lists in a simple array structure containing objects of my list.
Here's a small excerpt of the RemoteService
provider where i fetch the lists:
export class RemoteService<Type> {
public resource: string;
private actionUrl: string;
private headers: Headers;
constructor(private _http: Http) {
this.actionUrl = 'API_URL';
this.headers = new Headers();
this.headers.append('Content-Type', 'application/json');
this.headers.append('Accept', 'application/json');
}
public GetAll = (): Observable<Type[]> => {
return this._http.get(this.actionUrl + this.resource)
.map((response: Response) => <Type[]>response.json())
.catch(this.handleError);
}
}
When I decide to fetch all the lists on my Home page I then load them into an Observable Array
in the page's controller where I then map the result and instantiate every single object into a ListModel
.
export class HomePage {
lists: Observable<Array<ListModel>>;
listsObserver: any;
constructor(public nav: NavController, public remoteService: RemoteService<ListModel>) {
this.lists = Observable.create(observer => {
this.listsObserver = observer;
});
this.remoteService.resource = 'lists';
this.remoteService
.GetAll()
.subscribe((data:ListModel[]) => {
this.listsObserver.next(data.map(list => new ListModel(list.lid, list.title, list.items)));
},
error => console.log(error),
() => console.log('Get all Items complete'));
}
}
And a ListModel
looks like the following:
export class ListModel {
constructor(public lid: number, public title: string, public items: any[]) {
this.lid = lid;
this.items = items;
}
}
After doing all of this I started doubting myself if this is a good way to go about it. I want to understand how to really make correct use of angular 2..
So finally to my questions:
First of all, should I create the observer in the ListModel
instead of every page where I want to display or fetch my lists? Or should I create a separate ListCollection
for this purpose and then load it where I need it? If not the latter, then how should I think?
Then another bonus question, is it possible to cast the loaded object from the RemoteService
into a dynamic Model depending on where I load it? I read the top comment here and came to the conclusion that there should be a way to do this right?
Best regards,
Jake the Snake (not the wrestler)