以下代码片段是否相同?
function doSomething() {
var defer = $q.defer();
foo().then(function() {
bar().then(function() {
defer.resolve();
});
});
return defer.promise;
}
Run Code Online (Sandbox Code Playgroud)
function doSomething() {
return foo().then(bar);
}
Run Code Online (Sandbox Code Playgroud) 我需要在页面加载时加载一些数据,然后执行任务.为了获得我想要的数据,我执行多个不同的ajax调用.但是为了执行任务,我需要所有人确保所有的ajax调用都已完成.这是我到目前为止所做的:
$q.when(
$http.get('url1').success(function (data) {
$scope.data1 = data;
console.log("ajax1 finished");
}),
$http.get('url2').success(function (data) {
$scope.data2 = data;
console.log("ajax2 finished");
}),
$http.get('url3').success(function (data) {
$scope.data3 = data;
console.log("ajax3 finished");
}),
$http.get('url4').success(function (data) {
$scope.data4 = data;
console.log("ajax4 finished");
})
).then(
console.log("All ajax calls have finished!"),
executeTask()
);
Run Code Online (Sandbox Code Playgroud)
我的问题是在所有 ajax调用完成后,块中的代码then(...);不会被执行.我在我的控制台中得到这样的东西:
ajax2 finished
ajax1 finished
All ajax calls have finished!
ajax3 finished
ajax4 finished
Run Code Online (Sandbox Code Playgroud)
我一定做错了什么.我怎样才能让它按照我想要的方式工作?
编辑:我尝试了以下,就像答案中提到的那样,但我仍然面临同样的问题.
$q.all([
$http.get('url1').then(function (data) {
$scope.data1 = data;
console.log("");
}),
$http.get('url2').success(function (data) …Run Code Online (Sandbox Code Playgroud) 我试图将数据分配给$ scope变量.在我的$ promise.then()函数中,它正确显示但在函数外部显示为undefined.以下是我的控制器代码:
angular.module('testSiteApp').controller('TestController', function ($scope, Tests) {
$scope.test = Tests.get({id: 1});
$scope.test.$promise.then(function(data) {
$scope.tasks = data.tasks;
console.log($scope.tasks);
});
console.log($scope.tasks);
});
Run Code Online (Sandbox Code Playgroud)
then()函数内的结果:
[Object, Object, Object, Object]
Run Code Online (Sandbox Code Playgroud)
then()函数之外的结果:
undefined
Run Code Online (Sandbox Code Playgroud)
我正在使用的'Tests'服务工厂如下:
angular.module('testSiteApp').factory('Tests', function($resource) {
return $resource('/api/test/:id', {id: '@id'}, { 'update': { method: 'PUT' } } );
});
Run Code Online (Sandbox Code Playgroud)
即使我使用查询方法而不是get for my资源并将isArray设置为true,我仍然会遇到同样的问题.由于某种原因,数据没有绑定到then函数内的我的范围.
我很抱歉,如果这是一个重复的问题,但我到处寻找,只发现与$ promise函数有关的未定义问题,在这种情况下不是问题.
在此先感谢您的支持.
javascript angularjs angular-resource angularjs-scope angular-promise
承诺使用的模式仍然让我困惑.
例如,在Angular应用程序中,我有一个usersService带方法的服务emailExists(email).显然,它会向服务器执行请求,以检查给定的电子邮件是否已存在.
它感觉自然对我来说,使该方法emailExists(email)返回的承诺,在正常操作解析为true或false.如果我们只有一些意外错误(例如,服务器返回500: internal server error,则应拒绝承诺,但在正常操作中,它将被解析为相应的布尔值.
Hovewer,当我开始实现我的异步验证器指令(by $asyncValidators)时,我发现它想要解析/拒绝承诺.所以,到现在为止,我最终得到了这个相当丑陋的代码:
'use strict';
(function(){
angular.module('users')
.directive('emailExistsValidator', emailExistsValidator);
emailExistsValidator.$inject = [ '$q', 'usersService' ];
function emailExistsValidator($q, usersService){
return {
require: 'ngModel',
link : function(scope, element, attrs, ngModel) {
ngModel.$asyncValidators.emailExists = function(modelValue, viewValue){
return usersService.emailExists(viewValue)
.then(
function(email_exists) {
// instead of just returning !email_exists,
// we have to perform conversion from true/false
// to resolved/rejected promise
if (!email_exists){
//-- email does not …Run Code Online (Sandbox Code Playgroud) 在引用此链接之后,我正在尝试将JSON数据放入我的角度服务中.
服务:
.factory('restservice', ['$rootScope','$http', '$q', '$log',
function($rootScope,$q, $http) {
return {
getData: function() {
var defer = $q.defer();
$http.get('xyz.com/abc.php', { cache: 'true'})
.success(function(data) {
defer.resolve(data);
});
return defer.promise;
}
};
}])
Run Code Online (Sandbox Code Playgroud)
控制器:
.controller('RestaurantsCtrl', function ($scope,$http, restservice,restViewservice){
restservice.getData().then(function(data) {
$scope.Restaurants = data;
});
})
Run Code Online (Sandbox Code Playgroud)
实现此控制台后,'$ q.defer不是函数'.
这是什么问题?请帮忙 ...!!对于Angular Js来说,如果出现问题,请原谅.
我有一个服务,包含$ http我的函数返回一个延迟对象.
我的界面:
export interface MyServiceScope {
get: ng.IPromise<{}>;
}
Run Code Online (Sandbox Code Playgroud)
我的课:
export class MyService implements MyServiceScope {
static $inject = ['$http', '$log'];
constructor(private $http: ng.IHttpService,
private $log: ng.ILogService,
private $q: ng.IQService) {
this.$http = $http;
this.$log = $log;
this.$q = $q;
}
get(): ng.IPromise<{}> {
var self = this;
var deferred = this.$q.defer();
this.$http.get('http://localhost:8000/tags').then(
function(response) {
deferred.resolve(response.data);
},
function(errors) {
self.$log.debug(errors);
deferred.reject(errors.data);
}
);
return deferred.promise;
}
}
Run Code Online (Sandbox Code Playgroud)
编译失败,出现以下错误:
myservice.ts(10,18): error TS2420: Class 'MyService' incorrectly implements interface 'MyServiceScope'.
Types of …Run Code Online (Sandbox Code Playgroud) 我有以下链式承诺序列:
$scope.promisesInProgress = true
myService.myFirstPromise(id)
.then(function(data){
$scope.firstResponse = data;
return myService.mySecondPromise(id);
})
.then(function(data){
$scope.secondResponse = data;
})
.finally(function(){
$scope.promisesInProgress = false;
});
Run Code Online (Sandbox Code Playgroud)
finally()无论前两个承诺的成功/失败是什么,回调函数是否在最后被调用?
例如,如果myFirstPromise()返回400响应,mySecondPromise()将永远不会被调用 - 但我认为该finally()块仍然会被抛出?如果mySecondPromise()返回400(并且$scope.secondResponse从未设置)并且两个promises都返回200s,则应该如此.
我是angularjs的新手.我的目标非常简单.我想进行ajax调用以获取数据,并且一旦完成,我想再次调用以获取依赖于第一组信息的另一组数据.
我正在尝试利用promise机制这样做,以便我可以利用链接而不是嵌套的ajax调用,并且更好地保留具有我可以根据需要绑定在一起的独立函数的能力.
我的代码类似于以下内容:
var promiseGetWorkTypes = function ($q, $scope, $http) {
console.log("promiseGetWorkTypes");
return $q(function (resolve, reject) {
$http({
method: 'GET',
url: '/WorkTypes'
}).then(
function (payload) {
console.log("Got workttypegroups")
console.log(payload);
$scope.WorkTypeGroups = payload.data;
console.log("End of worktypegroups");
resolve(payload);
},
function (payload) {
reject(payload);
});
});
};
var promiseGetRecentActivities = function ($q, $scope, $http) {
console.log("promiseGetRecentActivities");
return $q(function (resolve, reject) {
$http({
method: 'GET',
url: '/RecentHistory'
}).then(
function (payload) {
$scope.RecentActivities = payload.data;
resolve(payload);
},
// data contains the response
// status is …Run Code Online (Sandbox Code Playgroud)$http和之间有什么区别$q?$q实施$http,反之亦然?$http,并$q在同一时间?我的承诺返回代码有问题,我有一个getTagQuotes包含for循环的函数,它可以使多个调用API将数据返回到数组中.
我的代码如何从下面开始:
// If there are tags, then wait for promise here:
if (tags.length > 0) {
// Setting promise var to getTagQuotes:
var promise = getTagQuotes(tags).then(function() {
console.log('promise =',promise);
// This array should contain 1-3 tags:
console.log('tweetArrayObjsContainer =',tweetArrayObjsContainer);
// Loop through to push array objects into chartObj:
for (var i=0; i<tweetArrayObjsContainer.length; i++) {
chartObj.chartData.push(tweetArrayObjsContainer[i]);
}
// Finally draw the chart:
chartDirective = ScopeFactory.getScope('chart');
chartDirective.nvd3.drawChart(chartObj.chartData);
});
}
Run Code Online (Sandbox Code Playgroud)
我的getTagQuotes函数带有promise返回:
function getTagQuotes(tags) {
var deferred = $q.defer(); // setting the …Run Code Online (Sandbox Code Playgroud) angular-promise ×10
angularjs ×10
javascript ×6
promise ×4
ajax ×2
angular-http ×1
deferred ×1
for-loop ×1
q ×1
typescript ×1