2016-05-20 8 views
2

私のコードで何を使用すべきか、そして約束をどのように使うべきかを理解することはできません。私の$ httpの呼び出しで。

私は、次のような機能

は最初、私は

$scope.getAcessToken() 

を呼びたいと私はアクセストークンを得れば、私は

$scope.getDataSets(lastSaved, cTime, accessToken) 

二つの機能があり、次の呼び出しを行うことになる持っています

$scope.getAcessToken = function() 
    { 
    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; 
     }) 
     .error(function(data,status){ 
     alert("ERROR: " + JSON.stringify(data) + status); 
     }); 
    } 
    else 
    { 
     $scope.firstTimeAuth(); 
    } 
    return accessToken; 
    } 

$scope.getDataSets = function(startTime, endTime, accessToken,) 
    { 
    $scope.a = "inside dataSets function"; 
    $url = "https://www.googleapis.com/fitness/v1/users/me/dataSources/derived:com.google.step_count.delta:com.google.android.gms:estimated_steps/datasets/" + startTime +"000000"+"-"+ endTime + "000000"; 
    alert("acess token is " + accessToken); 
    if(accessToken != "") 
    { 
     $http({method: 'GET', url: $url, 
         headers: {'Authorization': 'OAuth ' + accessToken},    
      }) 
      .success(function(response){ 
       alert("inside success block datasets"); 
       $scope.handleResponse(response); 
      }) 
      .error(function(response) { 
       alert("Something went wrong" + JSON.stringify(response)); 
      }); 
     } 
     else 
     { 
      alert("no access token received"); 
     } 
    } 

私は実際にそれを防ぐためにどのようにアクセストークン を取得する前にデータセットが実行されますを取得? EDIT 1:

$scope.firstTimeAuth = function(callback) { 
     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) { 
         accessToken = data.access_token; 
         refreshToken = data.refresh_token; 
         if(typeof(Storage) != "undefined") { 
          localStorage.setItem("refreshToken", refreshToken); 
          alert(localStorage.getItem("refreshToken")); 
         } else { 
          alert("Sorry, your browser does not support Web Storage..."); 
         } 
         //$location.path("/secure"); 
        }) 
       .error(function(data, status) { 
         alert("ERROR: " + data); 
        }); 
       ref.close(); 
      } 
     }); 
     callback(); 
    } 
+0

:あなたの要件ごとに下記($q doc link

は、最も可能性の高い実装コードです'firstTimeAuth'関数 – phuzi

+0

もう一つの注意点として、' 'success''と' '''''''''''約束メソッドを使用しないようにするべきです(https://docs.angularjs.org/api/ng/ service/$ http#deprecation-notice) – phuzi

+0

大丈夫です。私はこれにはかなり新しいです。だから、成功のブロックの代わりに何を使うべきかを確信していませんでした。 初めての認証はgetaccessTokenに似た関数で、$ httpも呼び出すことができます。とにかく病気を追加する – Shravan

答えて

2

あなたは全体の機能に約束を作るためにあなたの$scope.getAcessToken関数の内部延期使用する必要があります。これを動作させるには、コントローラーの依存関係に$qを追加する必要があります。あなたの関数は次のようになりましたになります。これが終了すると、$scope.getDataSetsを呼び出すように

$scope.getAcessToken = function(){ 
     alert("inside getAcessToken function"); 
     refreshToken = localStorage.getItem("refreshToken"); 
     var deferred = $q.defer(); 
    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; 
       deferred.resolve(true); 
      }) 
      .error(function(data,status){ 
       alert("ERROR: " + JSON.stringify(data) + status); 
       deferred.resolve(true); 
      }); 
     } 
     else 
     { 
      $scope.firstTimeAuth(); 
     } 
     return deferred.promise; 
     } 

今、あなたは、約束として、この機能を使用することができます。

$scope.getAcessToken().then(function(){ 
    $scope.getDataSets(); 
}); 
+0

答えをいただきありがとうございました。一度作業を終えると戻ってきます。もう一度感謝:) – Shravan

+0

[遅延反パターン](https://github.com/petkaantonov/bluebird/wiki/Promise-anti-patterns#the-deferred-anti-pattern)が使用されるたびに、約束が破られます。 – estus

1

anglejsが提供する$ qサービスを使用して、複数のメソッドの呼び出し順序を確認する必要があります。あなたがのためにコードを追加することができ、$ HTTPへの呼び出しによって生成された約束を返却する必要があるとしている

$scope.getAcessToken = function() 
    { 
    var deferral = $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){ 
      deferral.resolve({ accessToken: data.access_token }); 
     }) 
     .error(function(data,status){ 
     alert("ERROR: " + JSON.stringify(data) + status); 
     deferral.reject({ accessToken: data.access_token, error: JSON.stringify(data) + status}); 
     }); 
    } 
    else 
    { 
     $scope.firstTimeAuth(); 
    } 
    return deferral.promise; 
    } 

    $scope.getDataSets = function(startTime, endTime, accessToken,) 
    { 
    $scope.a = "inside dataSets function"; 
    $url = "https://www.googleapis.com/fitness/v1/users/me/dataSources/derived:com.google.step_count.delta:com.google.android.gms:estimated_steps/datasets/" + startTime +"000000"+"-"+ endTime + "000000"; 
    alert("acess token is " + accessToken); 
    if(accessToken != "") 
    { 
     $http({method: 'GET', url: $url, 
         headers: {'Authorization': 'OAuth ' + accessToken},    
      }) 
      .success(function(response){ 
       alert("inside success block datasets"); 
       $scope.handleResponse(response); 
      }) 
      .error(function(response) { 
       alert("Something went wrong" + JSON.stringify(response)); 
      }); 
     } 
     else 
     { 
      alert("no access token received"); 
     } 
    } 


    // making sure that $scope.getDataSets will be called when $scope.getAcessToken() call is completed 
    $q.when($scope.getAcessToken()).then(function(result) { 
        $scope.getDataSets(startTime, endTime, result.accessToken,); 
       }); 
+0

Nuriaが答えを –

+0

に打ち勝つように見えますが、これはそれを実装する別の方法です。 –

+0

答えをいただきありがとうございます。一度取り組むと一度元に戻ります。再度、感謝します :) – Shravan

関連する問題