本文介绍了$ q promises - 对象不是函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想从,这是我的代码:
I wanted to run the promises sample from https://docs.angularjs.org/api/ng/service/$q, here is my Code:
angular.module('testControllers').controller('testCtrl', ['$scope', '$q', function($scope, $q) {
function asyncGreet(name) {
// perform some asynchronous operation, resolve or reject the promise when appropriate.
return $q(function(resolve, reject) {
setTimeout(function() {
if (true) {
resolve('Hello, ' + name + '!');
} else {
reject('Greeting ' + name + ' is not allowed.');
}
}, 1000);
});
}
var promise = asyncGreet('Robin Hood');
promise.then(function(greeting) {
console.log('Success: ' + greeting);
}, function(reason) {
console.log('Failed: ' + reason);
});
}
Chrome一直告诉我:
TypeError:object不是函数
Chrome keeps telling me:TypeError: object is not a function
我对样本做错了什么?
推荐答案
制作确保你至少在版本1.3中使用angularjs请参阅下面的演示
Make sure that you using angularjs in version 1.3 at least please see demo below
var app = angular.module('app', [])
.controller('firstCtrl', function($scope, $q) {
$scope.ver = angular.version.full;
$scope.message = ""
$scope.asyncGreet = function (name) {
// perform some asynchronous operation, resolve or reject the promise when appropriate.
return $q(function(resolve, reject) {
setTimeout(function() {
if (true) {
resolve('Hello, ' + name + '!');
} else {
reject('Greeting ' + name + ' is not allowed.');
}
}, 1500);
});
}
promise = $scope.asyncGreet('Robin Hood');
promise.then(function(greeting) {
alert('Success: ' + greeting);
}, function(reason) {
alert('Failed: ' + reason);
});
});
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.0/angular.js"></script>
<div ng-app="app">
<div ng-controller="firstCtrl">
Angular ver: {{ver}}
</div>
</div>
这篇关于$ q promises - 对象不是函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!