Reputation: 275
I am new to typescript/ecma6 and would like to write this angular controller in typescript:
.controller('DashCtrl', function($scope, wpFactory) {
$scope.posts = [];
$scope.images = {};
wpFactory.getPosts(3).then(function (succ) {
$scope.posts = succ;
angular.forEach(succ, function(value, index) {
$scope.setUrlForImage(index, value.featured_image);
});
}, function error(err) {
console.log('Errror: ', err);
});
$scope.setUrlForImage = function(index, id) {
wpFactory.getMediaDataForId(id).then(function (succ) {
$scope.images[index] = succ.source_url;
});
};
})
with my actual approach I have problems with the scope of the methods in the class:
class DashCtrl {
public $inject = ['wpFactory'];
posts: any[];
images: any[];
constructor(public wpFactory: any) {
this.getPosts();
}
getPosts(){
... ?
}
setUrlForImage(succ:any, index:any, id:any){
... ?
}
}
The interesting part for me is how to develop the getPosts and the setUrlForImages method. Any suggestions would be appreciated.
Upvotes: 3
Views: 162
Reputation: 378
class DashCtrl {
public $inject = ['wpFactory'];
posts: any[];
images: any[];
constructor(public wpFactory: any) {
this.getPosts();
}
getPosts() {
this.wpFactory.getPosts(3).then(succ => {
this.posts = succ;
angular.forEach(succ, (value, index) => {
this.setUrlForImage(index, value.featured_image);
});
}, (err) => {
console.log('Errror: ', err);
});
}
setUrlForImage(succ:any, index:any, id:any) {
this.wpFactory.getMediaDataForId(id).then(succ => {
this.images[index] = succ.source_url;
});
}
}
Upvotes: 3