search
HomeWeb Front-endJS TutorialHow does angularjs determine whether rendering is complete? What happens with the $httpprovider service?

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 <h2 id="http-httpProvider-service">$http, $httpProvider service</h2><blockquote>https://docs. angularjs.org/ap...$http<br>https://www.cnblogs.com/keatk...</blockquote><p>$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. </p><p><strong>angular Default request header: </strong><br>Accept: application/json, text/plain accepts json and text<br>Content-Type: application/json<br>If you want to modify the default settings, you can make modifications in app.config</p><pre class="brush:php;toolbar:false">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>{{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
JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools