栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在Angular中阻止多个$ http请求。有没有更好的办法?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在Angular中阻止多个$ http请求。有没有更好的办法?

首先,我认为没有必要将其包装

HttpPromise
到另一个承诺中。在不赞成使用
success/error
方法的情况下,您应该仅依靠该方法,并将当作常规承诺。
then()``HttpPromise

为了确保只发送一次请求,您实际上可以跟踪

HttpPromise
创建的第一个请求,并在随后的函数调用中返回相同的promise。

这是一项服务,它将接受API端点作为参数,并确保仅向该API发送一个请求。

app.factory('$httpOnce', [ '$http', '$cacheFactory',  function ($http, $cacheFactory) {    var cache = $cacheFactory('$httpOnce');    return function $httponce(url, options) {      return cache.get(url) || cache.put(url, $http.get(url, options)        .then(function (response) {          return response.data;        }));    };  }]);

用法

function log(data) {  console.log(data);}// issues an HTTP request$httponce('https://api.github.com/').then(log);// does not issue an HTTP request, returns the same promise as above$httponce('https://api.github.com/').then(log);// ...// HTTP request completes somewhere, both promises above are resolved// ...setTimeout(function () {  // immediately resolved  $httponce('https://api.github.com/').then(log);}, 5000);

这是一个演示。您可以在开发工具中看到仅发出一个请求。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/386689.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号