简体   繁体   English

为什么我的诺言不能在angular js中工作?

[英]Why isnt my promise working in angular js?

Below is my angular controller but in it, my promise doesn't seem to work. 下面是我的角度控制器,但在其中,我的诺言似乎不起作用。 console.log isn't showing response nor is alert being shown over here. console.log没有显示响应,也没有在此处显示警报。

myapp.controller('contrl6', ['$scope','$q','$localStorage','$http',
  function ($scope,$q,$localStorage,$http) {

    $scope.myXhr = function(){

    var q = $q.defer();

     $http({
        method: 'GET',
         url: '/api/session_data'
        })
        .success(function(response){
            console.log(response);
            q.resolve('request successful');
        })
        .error(function(response){
          console.log("error");
            q.reject('ERROR');
        });


    return q.promise;
}
console.log("hi");

var myPromise = $scope.myXhr();
  myPromise.then(function(resolve){
        alert(resolve);
        console.log(resolve);
        }, function(reject){
        alert(reject);
        console.log(reject);      
    });


  }]);

Inside myxhr nothing is wired together with the result of $http . myxhr内部,没有任何东西与$http的结果连接在一起。 Don't worry about creating a new promise, because $http already returns one: 不必担心创建新的Promise,因为$http已经返回了一个:

$scope.myXhr = function(){

 return $http({
    method: 'GET',
     url: '/api/session_data'
    })
    .then(function(response){
        return response;
    })
    .catch(function(response){
        throw new Error('ERROR');
    });
}

Deprecation Notice 弃用通知

The $http legacy promise methods .success and .error have been deprecated. $http旧版.success方法.success.error已过时。 Use the standard .then method instead. 请使用标准的.then方法。 1 1

$scope.myXhrPromise = function(){
    return (
        $http({
            method: 'GET',
            url: '/api/session_data'
        }).then (function onFulfilled (response) {
            console.log(response.data);
            //return data for chaining
            return response.data;
        }).catch (function onRejected (response) {
            console.log(response.status);
            //throw to chain rejection
            throw response;
        })
    );
};

I copy/pasted your code into a Plunkr and it works just fine once I wire it up correctly. 我将您的代码复制/粘贴到Plunkr中,一旦正确连接,它就可以正常工作。

Plunkr example here 此处的Plunkr示例

As Duncan says, make sure you wire it up correctly, using ng-app and ng-controller. 正如Duncan所说,请确保使用ng-app和ng-controller正确连接。 If you can update your question with the HTML markup you're using perhaps we can help further. 如果您可以使用HTML标记更新您的问题,也许我们可以提供进一步的帮助。

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

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