【问题标题】:angular controller in typescript打字稿中的角度控制器
【发布时间】:2016-04-27 20:32:40
【问题描述】:

我是 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 方法。任何建议将不胜感激。

【问题讨论】:

    标签: javascript angularjs typescript ecmascript-6


    【解决方案1】:
    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;
        });
      }
    }
    

    【讨论】:

    • 修复格式?另外:也许提供一些关于 TypeScript 中 => 语法的信息。我的另一个问题是,您是否需要一些特殊的配置来允许可以使用this 访问$scope 的TS 类?
    • 大家好,感谢您的回答。不幸的是,这两种解决方案都不起作用。我对 getPosts() 中 this.setUrlImage 的实际代码的问题是:ts2346 - 提供的参数与调用目标的任何签名都不匹配。并且为调用 rest-service 生成的代码我想要的 id 是未定义的。
    • @froginvasion 看看这个stackoverflow.com/questions/25266555/… 的最后一个问题和developer.mozilla.org/en/docs/Web/JavaScript/Reference/… 箭头函数(=>)
    • 我认为 getPosts() 中 this.setUrlImage 中的“this”无法访问该类...但我不知道该怎么做。
    • 'this' 是 getPosts 中当前类实例的链接,如果从类实例调用 getPosts 方法,则可以访问 setUrlForImage 函数,如下所示:dashCtrlInstance.getPosts()
    猜你喜欢
    • 2016-03-08
    • 2015-07-19
    • 1970-01-01
    • 2015-03-21
    • 2015-06-23
    • 2013-08-16
    • 1970-01-01
    • 1970-01-01
    • 2016-02-03
    相关资源
    最近更新 更多