2016-12-18 12 views
0

私はAngularJSを使い始め、現在約束を見ています。だから私の古いコードは次のようになります。解決済みの約束をAngularJSのスコープに渡すにはどうすればよいですか?

app.controller('CustomerController', function ($scope Customers, $q) { 
    init(); 

    function init() { 
     Customers.getCustomers() 
     .then(function (response) { 
      $scope.customers = response.data; 
     }, function (error) { 
      console.log(error); 
     }); 
    } 
}); 

app.factory('Customers', function ($http) { 
    return { 
     getCustomers: function() { 
      return $http.get('/api/customers'); 
     } 
    }; 
}); 

それでは、私は約束を作るために私のinit関数でやったことは、このようなものです:

function init() { 
    var deferred = $q.defer(); 
    Customers.getCustomers() 
    .then(function (response) { 
     deferred.resolve(response.data); // how to pass this into my scope? 
    }, function (error) { 
     deferred.reject(error); 
    }); 
    return deferred.promise; 
} 

あなたが見ることができるように、私は渡すことができないんだけどそれは私の範囲にある。私はここで何か間違っていますか?

+0

を。 –

答えて

0

ここで何をしようとしているのか分かりません。しかし、このような約束をコントローラで使うのは意味がありません。あなたはこのようにどこかにあなたのinit関数を呼び出す必要があります:

init().then(response => $scope.data = response); 

あなたの古いコードでは、工場内の$ HTTPのGETメソッドは、サービスが約束を返して、あなたが正しくコントローラでの応答を処理します。

0

Angularの$ httpサービスがすでに約束を返すことを考慮してください。 $ http APIは、$ qサービスによって公開される遅延/約束APIに基づいています。 ですから、このようなものかもしれない:あなたは、コントローラを初期化する必要があるときに、APIからのいくつかのデータが必要な場合は、コントローラに初期化関数を呼び出して、手動でngRouteまたはuiRouter `resolve`属性を使用して、代わりに考慮

app.controller('CustomerController', function ($scope, Customers) { 
    init(); 

    function init() { 
     Customers.getCustomers() 
     .then(function (data) { 
      $scope.customers = data; 
     }, function (error) { 
      console.log(error); 
     }); 
    } 
}); 

app.factory('Customers', function ($http) { 
    return { 
     getCustomers: function() { 
      var promise = $http.get('/api/customers'). 
       then(function(response){ 
         return response.data; 
        }, 
        function(error) { 
         return response.error; 
        } 
       ) 

      return promise; 
     } 
    }; 
}); 
関連する問題