Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/77.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angularjs 无法从控制器延迟语句获取karma函数中的数据_Angularjs_Karma Jasmine_Angular Services - Fatal编程技术网

Angularjs 无法从控制器延迟语句获取karma函数中的数据

Angularjs 无法从控制器延迟语句获取karma函数中的数据,angularjs,karma-jasmine,angular-services,Angularjs,Karma Jasmine,Angular Services,我不会在业力测试中得到购物车物品。 控制器调用服务以异步方式获取数据。这个过程是 由angular promise处理。但编写测试用例>时出现问题,因为控制器函数在从>服务获取数据之前返回。 我怎样才能解决这个问题 替换 /*This is my cart service function:*/ getCheckoutItems: function() { var defer = $q.def

我不会在业力测试中得到购物车物品。 控制器调用服务以异步方式获取数据。这个过程是 由angular promise处理。但编写测试用例>时出现问题,因为控制器函数在从>服务获取数据之前返回。 我怎样才能解决这个问题

替换

            /*This is my cart service function:*/
            getCheckoutItems: function() {
                            var defer = $q.defer();
                            var response = {
                                result: true,
                                data: '',
                                err: ''
                            };
                            if (!angular.isUndefined(productListSample)) {
                                response.data = productListSample;
                                defer.resolve(response);
                            } else {
                                response.result = false;
                                response.err = 'error';
                                defer.reject(response);
                            }
                            return defer.promise;
                        }
        /*This is my controller function:*/
         $scope.cart = {
                    items: [],
                    phoneNo: ''
                };

                $scope.getCheckoutItems = function() {
                    CartService.getCheckoutItems().then(function(result) {
                        $scope.cart.items = result.data;
                                  }, function(err) {
                        /*
                         *  Todo: handle when service fails to retrieve data.
                         */
                    });
                };

    /* This is karma test function */
     it('get checkout items', inject(function($controller) {
        $controller('Ctrl', {
          $scope: scope
        });
        scope.getCheckoutItems();
        console.log(scope.cart);

      }));


Promise回调在作用域为$apply时被调用。

我对作用域有疑问。$apply()它到底做什么?在这种特定情况下,它将确保回调被调用。有关$apply()功能的完整说明,请阅读文档:
scope.getCheckoutItems();
console.log(scope.cart);
scope.getCheckoutItems();
scope.$apply();
console.log(scope.cart);