Home  >  Article  >  Web Front-end  >  How does angularjs determine whether rendering is complete? What happens with the $httpprovider service?

How does angularjs determine whether rendering is complete? What happens with the $httpprovider service?

寻∝梦
寻∝梦Original
2018-09-07 16:44:002041browse

This article is a note about angularjs. Sometimes I have found a solution to some problems before, but now I have forgotten it and I have to find the information again. Therefore, I will take this as a note now. No, they are all correct methods to use. Let’s take a look at them now

fromJson and toJson methods

angular.fromJson()The method is to convert json into an object or array of objects. The source code is as follows:

    function fromJson(json) {
        return isString(json) ? JSON.parse(json) : json  
    }

angular.toJson() The method is to convert an object or array into json. The source code is as follows:

    function toJson(obj, pretty) {
        return "undefined" == typeof obj ? undefined : JSON.stringify(obj, toJsonReplacer, pretty ? "  " : null)  
    }

promise

Angular's promise is provided and constructed by $q. $q provides a method for asynchronous execution by registering a promise project.

Handling asynchronous callbacks in JS is always very cumbersome and complicated:

// 案例1:在前一个动画执行完成后,紧接着执行下一个动画
$('xx').animate({xxxx}, function(){
    $('xx').animate({xx},function(){
        //do something
    },1000)
},1000)
// 案例2:jquery ajax 异步请求
$.get('url').then(function () {
    $.post('url1').then(function () {
      //do something
    });
});

Promise helps developers escape the abyss of deeply nested asynchronous callback functions. Angularjs provides and builds promises through the $q service. The most complete case:

   var defer1 = $q.defer();

   function fun() {
       var deferred = $q.defer();
       $timeout(function () {
           deferred.notify("notify");
           if (iWantResolve) {
               deferred.resolve("resolved");
           } else {
               deferred.reject("reject");
           }
       }, 500);
       return deferred.promise;
   }

   $q.when(fun())
       .then(function(success){
           console.log("success");
           console.log(success);
       },function(err){
           console.log("error");
           console.log(err);
       },function(notify){
           console.log("notify");
           console.log(notify);
       })
       .catch(function(reson){
           console.log("catch");
           console.log(reson);
       })
       .finally(function(final){
           console.log('finally');
           console.log(final);
       });

Promise call: $q.when(fun()).then(successCallback, errorCallback, notifyCallback); The abbreviation is: fun( ).then(successCallback, errorCallback, notifyCallback);

angularjs service encapsulation uses:

angular.module("MyService", [])
.factory('githubService', ["$q", "$http", function($q, $http){
    var getPullRequests = function(){
    var deferred = $q.defer();
    var promise = deferred.promise;
    $http.get("url")
    .success(function(data){
        var result = [];
        for(var i = 0; i < data.length; i++){
            result.push(data[i].user);
            deferred.notify(data[i].user); // 执行状态改变通知
        }
        deferred.resolve(result); // 成功解决(resolve)了其派生的promise。参数value将来会被用作successCallback(success){}函数的参数value。
        })
    .error(function(error){
        deferred.reject(error); // 未成功解决其派生的promise。参数reason被用来说明未成功的原因。此时deferred实例的promise对象将会捕获一个任务未成功执行的错误,promise.catch(errorCallback(reason){...})。
    });
    return promise;
}

return {
    getPullRequests: getPullRequests
};
}]);

angular.module("MyController", [])
    .controller("IndexController", ["$scope", "githubService",                                function($scope, githubService){
        $scope.name = "dreamapple";
        $scope.show = true;
        githubService.getPullRequests().then(function(result){
            $scope.data = result;
        },function(error){
        },function(progress){
           // 执行状态通知 notifyCallback
        });
    }]);

$http, $httpProvider service

https://docs. angularjs.org/ap...$http
https://www.cnblogs.com/keatk...

$http is an XMLHttpRequest request encapsulated by angular. Angular's thinking is biased toward restful concepts. Methods include: GET, POST, PUT, DELTE, PATCH, HEAD, etc.

angular Default request header:
Accept: application/json, text/plain accepts json and text
Content-Type: application/json
If you want to modify the default settings, you can make modifications in app.config

var app = angular.module("app", []);
app.config(function ($httpProvider) {           
    log(angular.toJson($httpProvider.defaults));
    $httpProvider.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
    $httpProvider.defaults.headers.put["Content-Type"] = "application/x-www-form-urlencoded";
    $httpProvider.defaults.headers.patch["Content-Type"] = "application/x-www-form-urlencoded";
});

As long as they are default headers, they will be included every time a request is sent. So if we use some custom headers for each request, we can also write them in default.headers. $httpProvider.defaults.headers.common["myHeader"] = "myheaderValue";//common means that regardless of any method POST, GET, PUT, etc.

These default headers are OK It is overwritten by parameters every time we make a request. In addition, $http service also provides a pointer to defaults (Note: $httpProvider.defaults === $http.defaults)

$ httpProvider.defaults.transformRequest & transformResponse

These are the two interfaces provided by angular. We do some processing on the post data and response data before the request is sent and before the response triggers the callback. They are arrays. Type, we can push some functions into it (angular puts a method into request and response by default. If the data is an object when posting, it will be jsonized, and when responding, if the data is of json type, it will be parsed into an object). On every request, we can still overwrite the entire array. (If you want to see more, go to the PHP Chinese website AngularJS Development Manual to learn)

var app = angular.module("app", []);
app.config(function ($httpProvider) {            
    $httpProvider.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
    $httpProvider.defaults.transformRequest.shift(); //把angular default的去掉
    $httpProvider.defaults.transformRequest.push(function (postData) { //这个function不是依赖注入哦
        if (angular.isObject(postData)) { 
            return $.param(postData); //如果postData是对象就把它转成param string 返回, 这里借用了jQuery方法
        }
        return postData;
    });
    $httpProvider.defaults.transformResponse.push(function (responseData) {
        log(angular.toJson(responseData)); //响应的数据可以做一些处理
        return "data";
    });
});
app.controller("ctrl", function ($scope, $http) {
    $http({
        method: "POST",
        url: "handle.ashx",
        data: {
            key: "value"
        },
        transformResponse: [], //每一次请求也可以覆盖default
        transformResponse: $http.defaults.transformResponse.concat([function () { return "abc" }]) //如果default要保留要concat
    }).success(function (responseData) {
        log(responseData === "abc"); //true
    });
});

$httpProvider.defaults.cache. Angular's default cahce = false, you can also set each request through defaults. We can also override settings on a per-request basis. When two uncached requests are sent at the same time, Angular can also handle it and only send it once.

var app = angular.module("app", []);
app.config(function ($httpProvider) {
    $httpProvider.defaults.cache = true;          
});
app.controller("ctrl", function ($scope, $http) {
    //并发但是只会发送一个请求
    $http.get("handle.ashx");
    $http.get("handle.ashx");
     
    //我们可以为每次请求要不要使用缓存或者缓存数据
    $http({
        url: "handle.ashx",
        method: "GET",
        cahce: true
    });
    $http({
        url: "handle.ashx", 
        method: "GET",
        cache : false //强制不使用缓存,即使已存在
    });
});

$httpProvider.interceptors
(interceptors means interception in Chinese). In addition to the transform introduced before, which can do some processing on the data, angular also provides four other moments, namely onRequest, onRequestFail, onResponse, and onResponseFail. Let's do some external processing. For example, when our server returns 500, maybe we want to make a general alert, or automatically adjust the config before trying the request if the request fails, etc.

//interceptors是数组,放入的是可以依赖注入的方法哦!
    $httpProvider.interceptors.push(["$q", function ($q) {
        return {
            request: function (config) { //config = {method, postData, url, headers} 等                            
                return config; //返回一个新的config,可以做一些统一的验证或者调整等.
            },
            requestError: function (rejection) {                      
                return $q.reject(rejection); //必须返回一个promise对象                                              
            },
            response: function (response) {                     
                return response; //这里也可以返回 promise, 甚至是把它给 $q.reject掉
            },
            responseError: function (rejection) { //rejection = { config, data, status, statusText, headers }                
                return $q.reject(rejection); //必须返回一个promise对象                  
            }
        };
    }]);

## The execution order of #transform is as follows interceptors.request -> transformRequest -> transformResponse -> interceptors.response##Determine whether the view is rendered completely


// 指令
app.directive('eventNgRepeatDone', function ($timeout) {
    return {
        restrict: 'A',
        link: function (scope, element, attr) {
            if (scope.$last) {
                // $timeout(function () {
                    scope.$emit('eventNgRepeatDone');
                    if ($attrs.ngRepeatDone) {
                        $scope.$apply(function () {
                            $scope.$eval($attrs.ngRepeatDone);
                        });
                    }
                //});
            }
        }
    }
});

<!-- 使用 -->
<p ng-repeat = "item in list track by $index" event-ng-repeat-done>{{item.name}}</p>

app.controller('myCtrl', ['$scope', function ($scope) {
    $scope.$on ('eventNgRepeatDone', function () {
        // doSomething
    });
});

Okay Okay, this article ends here (if you want to see more, go to the PHP Chinese website

AngularJS User Manual

to learn). If you have any questions, you can leave a message below.


The above is the detailed content of How does angularjs determine whether rendering is complete? What happens with the $httpprovider service?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn