神奇的angular

作者: 卿浅_ | 来源:发表于2017-04-07 12:59 被阅读24次

交互
$http —— 依赖项 ($scope $http)
$http.get();
$http.post();
$http.jsonp();
$http.get('请求地址').then((r)=>{
//成功
//r.data
},(err)=>{
//失败
});
Promise
1)基本用法,发一个请求
new Promise((resolve,reject)=>{ $.ajax({ url: dataType: success(r){ resolve(r); }, error(err){ reject(err); } }); }).then((r)=>{ //成功了 },(e)=>{ //失败了 });

2)Promise.all()
    Promise.all([
        //发请求的Promise对象
        new Promise(),
        new Promise(),
        ....
    ]).then(r=>{
        //以上数组中,指定的所有的请求,全部都成功,才是成功
    },err=>{
        //以上数组中,指定的所有的请求,只要有一个失败,就是失败
    });

    
3)发现 jquery 的 $.ajax 返回值,返回一个Promise对象
    Promise.all([
        $.ajax({url:'1',dataType:'json'}),
        $.ajax({url:'2',dataType:'json'}),
        $.ajax({url:'3',dataType:'json'}),
    ]).then(r=>{
        //r : 数组,多次请求返回结果的数组
        //单独处理每次请求的结果
        let [arr1,arr2,arr3] = r;
        console.log(arr1); —— 第一个请求的返回值 
        
    },err=>{});
4)
Promise.race([
    $.ajax(),
    $.ajax()....
]).then(r=>{
    r —— 以上所有的请求,最快的那个
},err=>{});```

PS:在Angular 中使用 Promise:

  • 1、angular中,使用原生的 Promise,出问题了
    在then里处理数据的时候,$scope.nums = arr1 生效,但是页面无法使用
  • 2、angular 自己提供了一个 Promise,
    新的依赖项: $q
    jQuery Ajax另几种写法:
    1、$.get('data/a.txt',{a:1},r=>{
    console.log(typeof r);
    });
    返回值是string类型
    2、$.post('data/a.txt',{a:1},r=>{
    console.log(typeof r);
    });
    返回值是string类型
    3、$.getJSON().....
    返回值是 json 对象
    Angular和其它库或原生的很多东西不通用:
    1) $.ajax jquery
    2) Promise 原生 $q
    3)定时器
    原理:因为函数,在Angular中,它认为所有的东西都应该出现在自己的controller函数里,
    对于其它地方回调函数里的值的处理,不认
    定时器:
    $interval
    $timeout
    解决以上问题的另外一个方法:
    $scope.$apply();
    ——通俗地说: 告诉、通知 Angular , 来看一下数据是不是变了

相关文章

网友评论

    本文标题:神奇的angular

    本文链接:https://www.haomeiwen.com/subject/usqrnttx.html