为什么vm没有绑定到这个?

时间:2016-06-12 00:34:12

标签: angularjs

function ExampleCtrl(HttpGet){
  'ngInject';

  const vm = this;
  vm.title = 'test';


  HttpGet.get().then(function(response){
    console.log(vm.title); //logs 'test';
    vm.response = response.data;
    console.log(vm.response); //logs the response;

  });

}

export  default {
  name : 'ExampleCrl',
  fn : ExampleCtrl
};

我的观点:

{{ home.response }} 

UI路由器:

  $stateProvider
  .state('Home', {
    url : '/home/:page',
    controller : 'ExampleCtrl as home',
    templateUrl: 'home.html',
    title : 'Home'
  });

HttpGet服务:

function HttpGet($http) {
  'ngInject';

  const service = {};

  service.get = function () {
    return new Promise(function(resolve, reject) {
      $http.get('http://localhost:8000/all').success((data) => {
        resolve(data);
      }).error((err, status) => {
        reject(err, status);
      });
    });
  };

  return service;

}

export default {
  name: 'HttpGet',
  fn: HttpGet
};

执行vm=this的重点不在于功能块this内仍然存在吗?

1 个答案:

答案 0 :(得分:2)

您的问题没有约束this。它工作正常。

您的问题是您离开了角度digest周期,因此您的html视图未更新。

  service.get = function () {
    return new Promise(function(resolve, reject) {
      $http.get('http://localhost:8000/all').success((data) => {
        resolve(data);
      }).error((err, status) => {
        reject(err, status);
      });
    });
  };

在此创建新承诺并将其命名为resolve功能。但它是原生的ES6承诺。当它被调用then处理程序时,它已经超出了角度摘要周期。

所以你应该使用

手动调用ditest
      $http.get('http://localhost:8000/all').success((data) => {
        $scope.$apply(() => resolve(data)); 
      }).error((err, status) => {

但是你可以更简单地解决这个问题,因为$http.get已经返回了一个承诺。只是做:

  service.get = function () {
    return $http.get('http://localhost:8000/all');
  };

这就是全部。 $http.get已经为您打电话摘要。

如果您真的需要在角度代码中创建承诺,那么请使用有角度的$q服务而不是ES6承诺,因为它已经考虑了摘要周期。

相关问题