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

AngularJs:在内部调用$ http或$ resource时,方法会同步返回

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

AngularJs:在内部调用$ http或$ resource时,方法会同步返回

一般来说,这是个坏主意。让我来告诉你为什么。浏览器中的Javascript基本上是单线程的野兽。想到它,它也是Node.js中的单线程。因此,您在开始等待远程请求成功或失败时不进行任何“返回”操作都可能涉及某种循环,以延迟请求之后的代码执行。像这样:

var semaphore = false;var superimportantInfo = null;// Make a remote request.$http.get('some wonderful URL for a service').then(function (results) {  superimportantInfo = results;  semaphore = true;});while (!semaphore) {  // We're just waiting.}// Code we're trying to avoid running until we know the results of the URL call.console.log('The thing I want for lunch is... " + superimportantInfo);

但是,如果您在浏览器中尝试这样做,并且调用花费了很长时间,那么浏览器会认为您的Javascript代码陷入了循环,并在用户的脸上弹出了一条消息,使用户可以停止代码。因此,Javascript的结构如下:

// Make a remote request.$http.get('some wonderful URL for a service').then(function (results) {  // Code we're trying to avoid running until we know the results of the URL call.  console.log('The thing I want for lunch is... " + results);});// Continue on with other pre which does not need the super important info or // simply end our Javascript altogether. The pre inside the callback will be // executed later.

这样的想法是,每当服务调用返回时,便会通过事件触发回调中的代码。因为事件驱动就是Javascript喜欢它的方式。Javascript中的计时器是事件,用户操作是事件,用于发送和接收数据的HTTP
/ HTTPS调用也会生成事件。并且您应该构建代码来响应这些事件。

在远程服务调用返回之前,您是否无法构造代码以使其认为canAccess为假,毕竟它确实是真的?我一直在AngularJS代码中这样做,我不知道我应该向用户显示的最终权限是什么,因为我还没有收到它们,或者我没有收到所有要显示在用户端的数据。首先。我有默认显示,直到真实数据返回,然后页面根据新数据调整为新格式。AngularJS的两种方式绑定使这确实非常容易。



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

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

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