【问题标题】:Execute code after callback ngResource回调ngResource后执行代码
【发布时间】:2015-10-02 03:24:30
【问题描述】:

我的控制器中有 ngResource create 的函数

app.controller 'CalculationsCtrl', ($scope, Calculation)->

  $scope.save = ()->
    $scope.busy = true
    Calculation.create($scope.calculation,
      (successResult)->
        console.log ("sucess")
      , (failResult)->
        console.log ("failrue")

    console.log("code after callbacks")
    $scope.busy = false

我想在执行.create 回调之后执行console.log("code after callbacks") 下面的代码。

我尝试使用.then,但似乎 ngResource 不支持它。

Calculation.create(...).then is not a function.

.then 等价于 ngResource 是什么?

【问题讨论】:

  • 为什么不在console.log("code after callbacks")下面添加你的代码?
  • @levi 它可能在回调之前执行。回调是异步的。
  • @levi 可能的输出是:“回调后的代码”“成功”当代码运行时

标签: javascript ruby-on-rails angularjs angularjs-rails


【解决方案1】:

$resource 实例(在您的情况下为 Calculation)有一个属性 $promise,您可以像往常一样在其上使用 .then

Calculation.create($scope.calculation).then(function (response) {
    ...
});

docs 中的最后一个示例也向您展示了它是如何完成的。

【讨论】:

    【解决方案2】:

    Angular $resource 返回一个可以使用 .then 的承诺。

    Calculation.create().$promise.then( function( response ) {
        console.log("success");
    }, function( error ) {
        console.log("error");
    );
    

    【讨论】:

      【解决方案3】:

      返回Calculation.create(...).then is not a function.,因为回调返回"strings"(来自console.log)。

      回调需要返回服务器响应。

      app.controller 'CalculationsCtrl', ($scope, Calculation)->

        $scope.save = ()->
          $scope.busy = true
          Calculation.create($scope.calculation,
            (successResult)->
              console.log ("sucess")
              successResult
            , (failResult)->
              console.log ("failrue")
              failResult
          ).$promise.then(
             function(succes){$scope...}, 
             function(fail){$scope...}
           )
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-03-05
        • 2022-11-01
        • 2015-08-02
        • 2015-08-13
        • 1970-01-01
        相关资源
        最近更新 更多