打字稿中的角度控制器

时间:2016-01-21 14:28:29

标签: javascript angularjs typescript ecmascript-6

我是typescript / ecma6的新手,想在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;
  });
};

})

根据我的实际方法,我对类中方法的范围有疑问:

class DashCtrl {

public $inject = ['wpFactory'];

posts: any[];
images: any[];

constructor(public wpFactory: any) {
  this.getPosts();
}
getPosts(){
  ... ?
}

setUrlForImage(succ:any, index:any, id:any){
  ... ?
}

}

对我来说有趣的部分是如何开发getPosts和setUrlForImages方法。任何建议将不胜感激。

1 个答案:

答案 0 :(得分:3)

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;
    });
  }
}