2017-02-06 8 views
2

私は、API URLをGETリクエストするための基本的な角度APPを持っています。返されるデータはJSON形式です。 APIドキュメントには、次のように記載されています。Angular JSは、リクエストごとにApp IDとKeyを渡します。

APIに入力するたびに、アプリケーションIDとキーを入力する必要があります。これを行うには、要求にHTTP IDヘッダーを設定します。IDには、コロンとキー(abc123:xyz789など)が続きます。

これを私の基本的なHTTPリクエストに組み込むにはどうすればいいですか?コードは以下の通りです。

このトピックを引用
angular.module('myApp', []) 
.controller('MyControler', function($scope, $http) { 
    $scope.$watch('search', function() { 
    fetch(); 
    }); 

    $scope.search = "My Search Query"; 

    function fetch() { 
    $http.get("https://APIURlGoesHere" + $scope.search) 
    .then(function(response) { 
     $scope.details = response.data; 
    }); 

    $http.get("ttps://APIURlGoesHere" + $scope.search) 
    .then(function(response) { 
     $scope.related = response.data; 
    }); 
    } 

}); 

答えて

1

最良の方法は次のとおりです。インターセプタ

便利な情報がありますhereおよびhere

ので、ここに:あなたのケースではAngularJS $http interceptors

、基本的には、次の実装(または同等)を持つファイルを作成する必要がありますし、あなたのプロジェクトに含まれます:

function myInterceptor() { 

    function request(req) { 

     var token = "mytoken" ; //<<--here you need to set the custom header's info (eg: abc123:xyz789) 
     var myHeader = "myHeader"; //<<--here you need to set the custom header's name (eg: Authorization) 

     if (token) { 
      //put custom header for sending the token along with every request 
      req.headers[myHeader] = token; 
     } 

     return req; 
    } 

    return { 
     request: request 
    }; 

}; 

function conf($httpProvider) { 
    $httpProvider['interceptors'].push('myInterceptor'); 
}; 

angular 
    .module('your_module_name') 
    .factory('myInterceptor', myInterceptor) 
    .config(['$httpProvider', conf]); 

これは、フロントエンドアプリからのすべてのリクエストを傍受し、そのヘッダーをそのアプリに含めます。

+0

これは素晴らしいと私はこれをテストし、あなたに戻って取得します。ありがとう – user1673498

+0

確かにそれは動作します。私はそれをたくさん使ってきました。それは魅力のように働く;) – lealceldeiro

+0

これは角1の権利ですか? – user1673498

1

How to use Basic Auth with jQuery and AJAX?

をので、角度で、それは次のようになります。これを実現するために、私がこれまで知っている

$http({ 
     method: "GET", 
     url: "https://APIURlGoesHere" + $scope.search, 
    headers: { 'Authorization' : 'Basic '+btoa(username + ":" + password) 
    }) 
.then(function(response) { 
    $scope.details = response.data; 
}); 
+0

このアプローチは不便です。実装されているすべてのサービスコールでヘッダーをこのように設定する必要があります。たとえば、ヘッダーの受信方法がAPIプロバイダによって変更された場合(非常に一般的ではありませんが、発生する可能性があります)、ヘッダーがこのように設定されているプロジェクトのすべてのファイルでこの実装を変更する必要があります何千もの)。とても素敵ではありません。 – lealceldeiro

関連する問題