简体   繁体   English

angular js中的异步调用

[英]asynchronous call in angular js

Hi all I am new to angular js,here I want to fetch the json from server to the controller so that I can handle the data,but whats happening here is the first alert -11 is called then alert 2 is called and in the end alert 1 is being called ,I read about promise so I tried it but still not working,I want it to happen one after another please help me .Thanks in advance 大家好,我是angular js的新手,在这里我想从服务器获取json到控制器,以便我可以处理数据,但是这里发生的是第一个警报-11被调用,然后警报2被调用,最后警报1正在被调用,我了解了诺言,所以我尝试了一下,但仍然没有用,我希望它一次又一次地发生,请帮助我。

sampleApp.controller('firstpage', function ($scope, $q, $http, $templateCache, onlinedata, offlinedata) {
    $scope.message = 'This is Add new order screen';
    var defer = $q.defer();
    defer.promise.then(function () {
        $scope.method = 'POST';
        $scope.url = 'http://ncrts.com/ncrtssales_compadmin/webservices/user_login';
        $scope.fetch = function () {
            $scope.code = null;
            $scope.response = null;
            alert($scope.response + 11) //alert11
            $http({
                method: $scope.method,
                url: $scope.url,
                cache: $templateCache
            }).
            success(function (data, status) {
                $scope.status = status;
                $scope.message = data;
                alert($scope.message + 1) //alert1
            }).
            error(function (data, status) {
                $scope.data = data || "Request failed";
                $scope.status = status;
            });
        };
        $scope.fetch();
    })
        .then(function () {
        alert($scope.message + 2); //alert 2
    })
    defer.resolve();
    //alert($scope.remember)
});

You have to use the resolve and reject functions to handle the response with the promise. 您必须使用resolve和reject函数来处理带有promise的响应。 You can find more information about promise in the AngularJS documentation . 您可以在AngularJS文档中找到有关Promise的更多信息。 I made a little change in your code to show you how you can achieve what you want. 我对您的代码进行了一些更改,以向您展示如何实现所需的功能。

sampleApp.controller('firstpage', function ($scope, $q, $http, $templateCache, onlinedata, offlinedata) {
$scope.message = 'This is Add new order screen';
var defer = $q.defer();

    $scope.method = 'POST';
    $scope.url = 'http://ncrts.com/ncrtssales_compadmin/webservices/user_login';

    $scope.fetch = function () {
        $scope.code = null;
        $scope.response = null;
        alert($scope.response + 11) //alert11

        var defer = $q.defer();
        $http({
            method: $scope.method,
            url: $scope.url,
            cache: $templateCache
        }).
        success(function (data, status) {
            //$scope.status = status;
            $scope.message = data;
            alert($scope.message + 1) //alert1
            defer.resolve({
               status: status,
               message: data
            });                
        }).
        error(function (data, status) {
            var data = data || "Request failed";
            //$scope.status = status;
            defer.reject({
               status: status,
               message: data
            });                             
        });
        return defer.promise;
    };

    $scope.fetch().then(function (data) {
        alert('Status: ' + data.status);
        alert('Message: ' + data.message);            
    });
});

I am very confused by the formatting of your code. 您的代码格式让我很困惑。 It may help you to write the asynchronous call in a service and then inject the service into your controller. 它可以帮助您将异步调用写入服务中,然后将服务注入到控制器中。 Keeping that in mind, here is some general advice that I've learned regarding asynchronous calls and promises in AngularJS: 请记住,这里是一些我在AngularJS中关于异步调用和Promise的一般建议:

  • Your service should initially return a deferred promise. 您的服务最初应返回延迟的承诺。 This promise should then be resolved on success() of the asynchronous call. 然后应在异步调用的success()上解决此承诺。
  • After $http() returns, but before success() returns, you have an unresolved promise. $http()返回之后,但在success()返回之前,您有未解决的承诺。 If you have code that you want to run after the promise is resolved, you need to use then() to indicate that you want to execute the code within the then() block once you've received data (and resolved the promise). 如果您有要解决承诺运行的代码,则需要使用then()表示一旦接收到数据(并解决了承诺), then()要在then()块内执行代码。
  • Not using then() for this situation will cause errors because you will be attempting to access data that doesn't yet exist. 在这种情况下不使用then()会导致错误,因为您将尝试访问尚不存在的数据。

It seems from your code that you are aware of the necessary coding strategy for what you need, but it will always help to isolate asynchronous calls into services so that the framework can make your life easier. 从您的代码看来,您已经了解了所需的必要编码策略,但是它将始终有助于将异步调用隔离到服务中,从而使框架可以使您的生活更轻松。 Good luck. 祝好运。

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

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