内置服务$q

2019-03-22  本文已影响0人  晨雪落客

$q是Angular的一种内置服务,它可以使你异步地执行函数,并且当函数执行完成时或异常时它允许你使用函数的返回值或返回执行状态通知等。

 defer的意思是延迟,$q.defer() 可以创建一个deferred延迟对象实例,实例旨在暴露派生的Promise 实例, Promise就是一种对执行结果不确定的一种预先定义,如果成功,就xx;如果失败,就xx,就像事先给出了一些承诺.

$q常用的几个方法:

  defer() 创建一个deferred对象,这个对象可以执行几个常用的方法,比如resolve,reject,notify等

  all() 传入Promise的数组,批量执行,返回一个promise对象

  when() 传入一个不确定的参数,如果符合Promise标准,就返回一个promise对象。

例如:

<!DOCTYPE html>

<html lang="en">

<head>

<meta  charset="UTF-8">

<title>angular gtest</title>

<script src="https://cdn.bootcss.com/angular.js/1.7.0/angular.min.js"></script>

<script src="https://cdn.bootcss.com/angular.js/1.7.0/angular-route.min.js"></script>

</head>

<body ng-app="myapp">

<header>

<p>内置服务器</p>

</header>

</body>

<div  ng-controller="helloCtrl">

<button ng-click="func()">点击我</button>

</div>

<script type="text/javascript">

//引用angular.js后,定义控制器,配置$q环境

        angular.module('myapp', []).controller('helloCtrl', ['$scope','$q','$timeout',function ($scope, $q, $timeout) {

$scope.func =function(){

//创建一个defer对象

            var defer =  $q.defer();

//获取promise对象

            var promise =defer.promise;

promise.then(function(e){

console.log('then1-success:' + e);//then1-success:成功1

            },function (e) {

console.log('then1-faild:' + e);

},function (e) {

console.log('then1-notice:' + e);//then1-notice:通知1 ,then1-notice:通知2

            }).then(function (e) {

console.log('then2-success:' + e);//then2-success:undefined

                throw "then2 exception";

}).catch(function(e){

console.log('catch:' + e);// catch:then2 exception

            }).finally(function(e){

console.log('finally:' + e);//finally:undefined

            });

defer.notify("通知1");

defer.notify("通知2");

defer.resolve('成功1');

defer.reject('失败1');

//执行结果:

/**

* then1-notice:通知1

then1-notice:通知2

then1-success:成功1

then2-success:undefined

catch:then2 exception

finally:undefined

*/

        }

}]);

</script>

</html>

上一篇 下一篇

猜你喜欢

热点阅读