在 Angular 中使用“Controller as"模式时回调中的数据 [英] Data in callback when using 'Controller as' pattern in Angular

查看:19
本文介绍了在 Angular 中使用“Controller as"模式时回调中的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有最简单的角度控制器:

tc.controller('PurchaseCtrl', function () {var 购买 = 这个;purchase.heading = '高级功能';this.onSuccess = 函数(响应){console.log('成功', 响应);lib.alert('success', 'Success: ', '已加载可用产品列表...');购买.productList = 响应;};this.onFail = 函数(响应){console.log('失败', 响应);};console.log('google.payments.inapp.getSkuDetails');lib.alert('info', 'Working: ', '检索可用产品列表...');google.payments.inapp.getSkuDetails({'参数':{'环境':'产品'},成功":购买.onSuccess,'失败':purchase.onFail});});

和视图:

{{购买}}

打印出来:

{"heading":"高级功能"}

我认为当回调返回时,视图将更新为任何新数据.我错过了什么吗?回调返回,我在控制台中看到了 dtaa.

使用 $scope 模式我想我会使用 $scope.$apply 到异步方法,但我不知道如何在这里做.

解决方案

使用 controllerAs 不会改变摘要循环的工作方式或任何事情.它只是一个将属性(使用时名称与别名相同)添加到当前作用域的糖,其值指向控制器实例引用.因此,您需要手动调用摘要循环(使用 scope.$apply[Asyc]() 或什至使用虚拟的 $timeout(angular.noop,0)$q.when() 等)在这种情况下也是如此.但是您可以通过将范围抽象为一个角度服务并从那里返回一个承诺来避免注入范围,即

myService.$inject = ['$q'];函数 myService($q){//传递数据并在需要的地方使用它this.getSkuDetails = 函数(数据){//创建延迟对象var defer = $q.defer();//你甚至可以把这个全局变量`google`放在一个//常量或注入它以获得更干净的代码和可测试性.google.payments.inapp.getSkuDetails({'参数':{'环境':'产品'},成功":函数成功(响应){defer.resolve(response);//用值解析},'失败':函数错误(响应){延迟拒绝(响应);//拒绝有值}});//返回承诺返回 defer.promise;}}//将服务注册为服务

现在将 myService 注入您的控制器并将其用作:

 myService.getSkuDetails(data).then(function(response){购买.productList = 响应;}).catch(函数(错误){//处理错误});

I have the simplest angular controller:

tc.controller('PurchaseCtrl', function () {
    var purchase = this;
    purchase.heading = 'Premium Features';

    this.onSuccess = function (response) {
      console.log('Success', response);
      lib.alert('success', 'Success: ', 'Loaded list of available products...');
      purchase.productList = response;
    };
    this.onFail = function (response) {
      console.log('Failure', response);
    };

    console.log('google.payments.inapp.getSkuDetails');
    lib.alert('info', 'Working: ', 'Retreiving list of available products...');
    google.payments.inapp.getSkuDetails(
      {
        'parameters': {'env': 'prod'},
        'success': purchase.onSuccess,
        'failure': purchase.onFail
      });

  });

And the view:

<div class="col-md-6 main" ng-controller="PurchaseCtrl as purchase">
    {{purchase}}
</div>

This prints out:

{"heading":"Premium Features"}

I thought that when the callback returned, the view would be update with any new data. Am I missing something? The callback returns and I see the dtaa in the console.

Using the $scope pattern I think that I would use $scope.$apply to async method, but I'm not sure how to do that here.

解决方案

Using controllerAs does not change the way digest cycle works or anything. It is just a sugar that adds a property (with the name same as alias name when used) to the current scope with its value pointing to the controller instance reference. So you would need to manually invoke the digest cycle (using scope.$apply[Asyc]() or even with a dummy $timeout(angular.noop,0) or $q.when() etc) in this case as well. But you can avoid injecting scope by abstracting it out into an angular service and returning a promise from there, i.e

myService.$inject = ['$q'];
function myService($q){
  //pass data and use it where needed
  this.getSkuDetails = function(data){ 
     //create deferred object
     var defer = $q.defer();
     //You can even place this the global variable `google` in a 
     //constant or something an inject it for more clean code and testability.
     google.payments.inapp.getSkuDetails({
        'parameters': {'env': 'prod'},
        'success': function success(response){
            defer.resolve(response);// resolve with value
         },
        'failure': function error(response){
            defer.reject(response); //reject with value
         }
      });
     //return promise
     return defer.promise;
  }
}
//Register service as service

Now inject myService in your controller and consume it as:

   myService.getSkuDetails(data).then(function(response){
         purchase.productList = response;
   }).catch(function(error){
      //handle Error
   });

这篇关于在 Angular 中使用“Controller as"模式时回调中的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆