Reputation: 3175
I'm having trouble mapping an http object to a model of mine, here's what I'm working with:
MyObjController.ts
class MyObjController {
constructor (
private myObj:myObjService,
private $scope:angular.IScope,
private modal,
private notifier,
private $translate,
private $state,
public items:MyObjModel[],
public loading
) {
this.loading = this.myObj.all();
this.loading.then((allItems) => {
this.items = allItems;
});
}
}
MyObjService.ts
all () : angular.IPromise<MyObjModel[]> {
let uri = `/myuri`;
return this.api.get(uri).then((response:any) => {
return _.map(response.data, MyObjModel.create);
});
}
MyObjModel.ts
export class MyObjModel {
constructor () { }
id:string;
name:string = '';
organizationId:string = '';
static create (apiResponse) {
let model = new MyObjModel();
model.id = apiResponse.Id;
model.name = apiResponse.Name;
model.organizationId = apiResponse.OrganizationId;
return model;
}
}
This approach isn't working since _.map is sending each value from my response.data and creating a new instance of MyObjModel for each of the properties and then creating an array of the models. I'm looking for a way to send response.data as a whole to my create() function and have it map the values to a single instance of the model and return that single model.
Thanks in advance!
Upvotes: 0
Views: 546
Reputation: 41571
You should be using the below code,
all () : angular.IPromise<MyObjModel[]> {
let uri = `/myuri`;
return this.api.get(uri).map(data=><MyObjController>data.json())).toPromise();
});
}
You can use interface instead of class and constructor which is the recommended practice as well
Upvotes: 1