Table of Contents
fromJson and toJson methods
promise
$http, $httpProvider service
Okay Okay, this article ends here (if you want to see more, go to the PHP Chinese website
Home Web Front-end JS Tutorial 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?

Sep 07, 2018 pm 04:44 PM
angularjs

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  
    }
Copy after login

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)  
    }
Copy after login

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)
Copy after login
// 案例2:jquery ajax 异步请求
$.get('url').then(function () {
    $.post('url1').then(function () {
      //do something
    });
});
Copy after login

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);
       });
Copy after login

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
        });
    }]);
Copy after login

$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";
});
Copy after login

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
    });
});
Copy after login

$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 //强制不使用缓存,即使已存在
    });
});
Copy after login

$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对象                  
            }
        };
    }]);
Copy after login

## 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
    });
});
Copy after login

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 of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

The latest 5 angularjs tutorials in 2022, from entry to mastery The latest 5 angularjs tutorials in 2022, from entry to mastery Jun 15, 2017 pm 05:50 PM

Javascript is a very unique language. It is unique in terms of the organization of the code, the programming paradigm of the code, and the object-oriented theory. The issue of whether Javascript is an object-oriented language that has been debated for a long time has obviously been There is an answer. However, even though Javascript has been dominant for twenty years, if you want to understand popular frameworks such as jQuery, Angularjs, and even React, just watch the "Black Horse Cloud Classroom JavaScript Advanced Framework Design Video Tutorial".

Use PHP and AngularJS to build a responsive website to provide a high-quality user experience Use PHP and AngularJS to build a responsive website to provide a high-quality user experience Jun 27, 2023 pm 07:37 PM

In today's information age, websites have become an important tool for people to obtain information and communicate. A responsive website can adapt to various devices and provide users with a high-quality experience, which has become a hot spot in modern website development. This article will introduce how to use PHP and AngularJS to build a responsive website to provide a high-quality user experience. Introduction to PHP PHP is an open source server-side programming language ideal for web development. PHP has many advantages, such as easy to learn, cross-platform, rich tool library, development efficiency

Build web applications using PHP and AngularJS Build web applications using PHP and AngularJS May 27, 2023 pm 08:10 PM

With the continuous development of the Internet, Web applications have become an important part of enterprise information construction and a necessary means of modernization work. In order to make web applications easy to develop, maintain and expand, developers need to choose a technical framework and programming language that suits their development needs. PHP and AngularJS are two very popular web development technologies. They are server-side and client-side solutions respectively. Their combined use can greatly improve the development efficiency and user experience of web applications. Advantages of PHPPHP

Build a single-page web application using Flask and AngularJS Build a single-page web application using Flask and AngularJS Jun 17, 2023 am 08:49 AM

With the rapid development of Web technology, Single Page Web Application (SinglePage Application, SPA) has become an increasingly popular Web application model. Compared with traditional multi-page web applications, the biggest advantage of SPA is that the user experience is smoother, and the computing pressure on the server is also greatly reduced. In this article, we will introduce how to build a simple SPA using Flask and AngularJS. Flask is a lightweight Py

How to use AngularJS in PHP programming? How to use AngularJS in PHP programming? Jun 12, 2023 am 09:40 AM

With the popularity of web applications, the front-end framework AngularJS has become increasingly popular. AngularJS is a JavaScript framework developed by Google that helps you build web applications with dynamic web application capabilities. On the other hand, for backend programming, PHP is a very popular programming language. If you are using PHP for server-side programming, then using PHP with AngularJS will bring more dynamic effects to your website.

Use PHP and AngularJS to develop an online file management platform to facilitate file management Use PHP and AngularJS to develop an online file management platform to facilitate file management Jun 27, 2023 pm 01:34 PM

With the popularity of the Internet, more and more people are using the network to transfer and share files. However, due to various reasons, using traditional methods such as FTP for file management cannot meet the needs of modern users. Therefore, establishing an easy-to-use, efficient, and secure online file management platform has become a trend. The online file management platform introduced in this article is based on PHP and AngularJS. It can easily perform file upload, download, edit, delete and other operations, and provides a series of powerful functions, such as file sharing, search,

Introduction to the basics of AngularJS Introduction to the basics of AngularJS Apr 21, 2018 am 10:37 AM

The content of this article is about the basic introduction to AngularJS. It has certain reference value. Now I share it with you. Friends in need can refer to it.

How to use PHP and AngularJS for front-end development How to use PHP and AngularJS for front-end development May 11, 2023 pm 05:18 PM

With the popularity and development of the Internet, front-end development has become more and more important. As front-end developers, we need to understand and master various development tools and technologies. Among them, PHP and AngularJS are two very useful and popular tools. In this article, we will explain how to use these two tools for front-end development. 1. Introduction to PHP PHP is a popular open source server-side scripting language. It is suitable for web development and can run on web servers and various operating systems. The advantages of PHP are simplicity, speed and convenience

See all articles