简体   繁体   English

用Javascript返回值,但结果未定义

[英]Return value in Javascript but it turns out to be undefined

I'm new at Javascripts and i'm trying to use Angular UI route, here is my code 我是Java语言的新手,正在尝试使用Angular UI路由,这是我的代码

myApp.config(['$stateProvider', '$urlRouterProvider',function($stateProvider, $urlRouterProvider) {     
    $stateProvider  
        .state('home', {
            url: '/test',
            templateUrl: '/custom.html'
        })
        .state('detail', {                
            url: '/{examID}',              
            views: {
            '': {
              templateUrl: '/templates/customize.html',
               controller: ['$scope', '$stateParams', 'utils',

                function ( $scope,$stateParams,utils) {
                  $scope.exam = utils.findById($stateParams.examID);
                  console.log('exam is ' + $scope.exam );
                }
                ]
        }            
            }
        }     )    

    }])

and this is the service which has findbyID function 这是具有findbyID功能的服务

angular.module('service', [])
.factory('utils', function ( $http) {
  return {
    findById: function findById(id) {
       $http.get('/api/exams/' + id).success(function(response) {
            return response;
    })}
};});

i've already follwed this topic but $scope.exam still undefined 我已经关注了这个话题,但是$ scope.exam仍未定义

How to return value from an asynchronous callback function? 如何从异步回调函数返回值?

PS. PS。 i've tried to print out response and it's an object 我试图打印出响应,这是一个对象

Thx 谢谢

This is a place where a lot of developers new to JavaScript stumble. 这是很多不熟悉JavaScript的开发人员绊脚石的地方。

What is going on here is that you are assigning the return value of utils.findById() to $scope.exam . 这里发生的是您正在将utils.findById()的返回值分配给$scope.exam The problem is that utils.findById() doesn't actually return anything. 问题在于utils.findById()实际上未返回任何内容。 (When a function doesn't have an explicit return statement in JavaScript, the return value is implicitly undefined .) (当函数在JavaScript中没有显式的return语句时,返回值将隐式undefined 。)

Here is what your service should look like: 您的服务应如下所示:

angular
  .module('service', [])
  .factory('utils', function ($http) {
    return {
      findById: function (id) {
        return $http.get('/api/exams/' + id);
      }
    };
  });

You probably noticed that the call to .success() has disappeared too! 您可能已经注意到对.success()的调用也消失了! Don't worry. 不用担心 It just moved. 它刚刚移动。

Instead of calling .success() on $http.get() , we want to call it on utils.findById() . 与其在$http.get() .success()上调用.success()$http.get()utils.findById()上调用它。 Doing this will give you access to the response variable in your controller. 这样做将使您可以访问控制器中的response变量。 Because you will have access to the response variable, you will be able to assign response to $scope.exam like so: 因为您将有权访问response变量,所以您可以将response分配给$scope.exam如下所示:

.state('detail', {
  url: '/{examID}',
  views: {
    '': {
      templateUrl: '/templates/customize.html',
      controller: ['$scope', '$stateParams', 'utils',
        function ($scope, $stateParams, utils) {
          utils.findById($stateParams.examID)
            .success(function (response) {
              $scope.exam = response;
            });
        }
      ]
    }
  }
});

Hopefully that cleared it up. 希望这一点可以解决。 If I haven't been clear on anything, please let me know so I can update this answer. 如果我不清楚,请告诉我,以便我更新此答案。

You have to wait for the ajax call to finish. 您必须等待ajax调用完成。 Modify the code in your controller to: 修改控制器中的代码以:

$scope.exam;
utils.findById($stateParams.examID).then(function(data) {
    $scope.exam = data.data;
}

Read about the concept of ' Promises ' in AngularJS and JavaScript. 阅读AngularJS和JavaScript中的“ Promises ”概念。

Use deferred promise, So that it would return value after response 使用延迟的promise,以便在响应后返回值

Service: 服务:

angular.module('service', [])
.factory('utils', function ( $http) {
  return {
    findById: function findById(id) {
       var promise=$http.get('/api/exams/' + id);
   return promise;
};});

Controller: 控制器:

   myApp.config(['$stateProvider', 
  '$urlRouterProvider',function($stateProvider, $urlRouterProvider) {     
            $stateProvider  
                .state('home', {
                    url: '/test',
                    templateUrl: '/custom.html'
                })
                .state('detail', {                
                    url: '/{examID}',              
                    views: {
                    '': {
                      templateUrl: '/templates/customize.html',
                       controller: ['$scope', '$stateParams', 'utils',

                        function ($scope, $stateParams, utils) {
                                                   utils.findById($stateParams.examID).then(function(value) {
                        $scope.exam = value;
                        console.log('exam is ' + $scope.exam );
                         });

                        }
                        ]
                       }           
                    }
                })    
        }])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM