编辑:我上次在浏览器控制台中检查时收到这样的错误。
TypeError:无法读取属性'延迟'未定义的
我需要调用一个$ http请求,该请求提供可用于调用另一个$ http请求的令牌,最后是所需的响应。
因此我使用promises使它同步工作。但是在$q.defer()
函数之后函数没有被执行
以下是我的代码:
$scope.firstTimeAuth = function($q) {
var deferred = $q.defer();
var ref = window.open('https://accounts.google.com/o/oauth2/auth?client_id=' + clientId + '&redirect_uri=http://localhost/callback&scope=https://www.googleapis.com/auth/fitness.activity.write &approval_prompt=force&response_type=code&access_type=offline', '_blank', 'location=no');
ref.addEventListener('loadstart', function(event) {
if((event.url).startsWith("http://localhost/callback")) {
requestToken = (event.url).split("code=")[1];
$http({
method: "post", url: "https://accounts.google.com/o/oauth2/token",
data: "client_id=" + clientId + "&client_secret=" + clientSecret + "&redirect_uri=http://localhost/callback" + "&grant_type=authorization_code" + "&code=" + requestToken
})
.success(function(data) {
defer.resolve(true);
accessToken = data.access_token;
refreshToken = data.refresh_token;
alert("firstTimeAuth success");
if(typeof(Storage) != "undefined") {
localStorage.setItem("refreshToken",refreshToken);
alert(localStorage.getItem("refreshToken"));
} else {
alert("Sorry, your browser does not support Web Storage...");
}
//functions here
})
.error(function(data, status) {
alert("ERROR: " + data);
defer.resolve(true);
});
ref.close();
}
});
return deferred.promise;
}
这是我的第二个功能
$scope.getAcessToken = function($q)
{
var deferred = $q.defer();
alert("inside getAcessToken function");
refreshToken = localStorage.getItem("refreshToken");
if(refreshToken)
{
$http({
method: "post", url: "https://accounts.google.com/o/oauth2/token",
data: "client_secret=" + clientSecret + "&grant_type=refresh_token" + "&refresh_token="+ refreshToken + "&client_id=" + clientId
})
.success(function(data){
accessToken = data.access_token;
alert("getAcessToken success" + accessToken);
deferred.resolve(true);
})
.error(function(data,status){
alert("ERROR: " + JSON.stringify(data) + status);
deferred.resolve(true);
});
}
else
{
$scope.firstTimeAuth();
}
return deferred.promise;
}
我称之为。
alert("not installed");
var lastSaved = $scope.getFirstEpochTime();
//walkthroug
//Registe
$scope.firstTimeAuth().then(function(){
alert("firstime done");
$scope.getDataSets().then(function(){
alert(" in the last block");/*
$scope.handleResponse().then(function(){
$scope.insert().then(function(){
$scope.select();
})
alert("done in installed");
})
*/})
})
请告诉我代码有什么问题。我对此很新...谢谢。
答案 0 :(得分:1)
您是否在$q
首先注入了controller
。
angular.module('module.name').controller('ControllerName',
['$scope', '$q', function ($scope, $q) {
}]);
我真的不明白你为什么要将$q
传递给你的功能,你不需要这样做。 $scope.firstTimeAuth = function($q) {
答案 1 :(得分:1)
通过定义函数的参数,您可以创建一个局部变量,该变量隐藏外部作用域中具有相同名称的任何内容。在您的情况下,您要定义:
$scope.firstTimeAuth = function($q) {}
然后你在许多地方像$scope.firstTimeAuth();
一样调用它。由于您没有传递任何内容,因此函数范围中的$q
将是未定义的。您只应将其注入整个控制器范围并删除范围方法中指定的此类参数,以便它不会隐藏注入的服务。
或者如果你因某些原因必须传递它们,那就正确地做好。