Asynchronus calls in angularjs
Asynchronus calls in angularjs
我是Javascript和Angularjs的新手。我想知道,如何异步调用一个函数而不等待它从中返回。
请让我知道,如果有一些例子,那将非常有帮助。
问候议员
使用 Angular 的deferred
:
function myAsyncFunction() {
var deferred = $q.defer();
//..
setTimeout(function() {
deferred.resolve({ message: "resolved!" });
// or deferred.reject({ message: "something went terribly wrong!!" });
}, 1000);
//..
return deferred.promise;
}
myAsyncFunction()
.then(function(data){
// success
console.log("success", data.message);
}, function(data) {
// fail
console.log("error", data.message);
}).finally(function() {
// always
});
您可以使用延迟返回承诺,然后在函数完成后解析承诺。尝试这样的事情:
http://jsfiddle.net/adcoxwga/
var myApp = angular.module('myApp',[])
.service('myService', function($q, $timeout){
this.someFunction = function(){
var deferred = $q.defer(); //making a new deferred
$timeout(function(){
deferred.resolve('something'); //resolving the deferred with a response
}, 3000);
return deferred.promise; //returning a promise
}
})
.controller('MyCtrl', function($scope, myService){
myService.someFunction().then(function(response){ //calling the asynchronous function
console.log(response); //getting response
}, function(error){
console.log(error); //getting error
});
});
你有几个不同的选择摆在你面前,但需要注意的一件事是你必须对异步活动使用回调或承诺。由于您使用的是角度,因此我建议使用promise。
使用承诺
如果要编写对 API 的 http 调用,则可以使用 $http
或 $resource
。如果你开始研究角度提供者,你会看到$http
返回一个承诺,而$resource返回一个承诺,但你必须专门调用它才能访问它。例如:
一些服务
function someServiceFunction () {
return $http.get('some/url');
}
某控制器
$scope.results = [];
someService.someServiceFunction().then(function(data) {
$scope.results = data;
});
需要注意的是,第一个返回的函数是成功场景,如果你声明第二个回调,那么它就是失败场景。
如果要在同一方案中使用回调:
使用回调
一些服务
function someServiceFunction (callback) {
return $http.get('some/url')
.success(callback);
}
某控制器
$scope.results = [];
someService.someServiceFunction(function(data, status, headers, config) {
$scope.results = data;
});
下面是指向$http提供程序的链接。下面是指向$resource提供程序的链接。
干杯!
相关文章:
- Instagram oauth flow in angularjs
- AngularJS.Filter in ng中的多个条件重复
- angularjs formly submit bug in safari & IE 11
- 如何获得家长's的父's的父's id in Angularjs
- 进度条与 ngRoute in angularjs.
- Jquery in AngularJs
- ng-class not working properly in 'AngularJs'
- AngularJS-ngRepeat对对象的返回顺序与vanillar.in循环不同
- AngularJs: ng-repeat="item in arrayValue"
- AngularJS promise in app.run()
- limitTo not working in ng-repeat in AngularJs
- AngularJS "localStorage.getItem" is null in $resou
- ElasticSearch to NVD3 in Angularjs
- Angularjs with dynamic model in ng-repeat
- Defer 和 Promise in angularjs 无法正常工作
- Angularjs in sharepoint 365
- Angularjs in rails:在不重新加载的情况下更改页面
- Shortening for AngularJS in javascript
- Angularjs in rails:添加数据到数据库并显示,而不需要重新加载
- AngularJS in Confluence