2013-06-18 44 views
7

私は妥当な質問のようなものには答えられないようです。

私はすべてのアプリケーションのWebサービスを呼び出すために$ httpサービスを使用しています。すべてのサーバーAPIは、特定のアドレスでホストされています。提供されたURLにAPIサーバーを常に接頭辞として付けるように$ httpを取得する方法はありますか?

$http.get("http://myAPI/API/User") 

と角度プレフィックスサーバアドレスで要求を:とは対照的に、

$http.get("User")... 

例えば、私のAPIがhttp://myAPi/API/であるならば、私が呼び出すことができるようにしたいと思います。その目的は、URLがアプリ全体に広がらないようにすることです。

角度を使ってこれを達成する方法はありますか? $ HTTPは(angular.jsソースコードを編集する以外の)このケースを処理する組み込みの方法を持っていないので

+0

いくつかの時間前[の可能な重複を解決をしましたin AngularJS](http://stackoverflow.com/questions/17011616/using-a-relative-path-for-a-service-call-in-angularjs) – Stewie

+0

私は現在持っている重複する可能性のある詳細 - 本質的にサーバーの場所何らかの種類の変数に格納され、各呼び出しに手動で接頭辞が付けられます。私は接頭辞が自動的に前置される方法を探しています(可能ならば)。 – jwest

答えて

4

、あなたはサービスであなたの$ HTTPをラップすることができ、次のいずれか

apiService.get('user'); //where the service defines the $http call and builds the URL 

どちらの方法は、「アプリを通じてURLの広がりを持っていない」につながる

angular.module('myApp', []).constant('apiPrefix', 'http://myAPI/API/') 

$http.get(apiPrefix + 'User') 

:...または単に角度の定数を作成します。

-1

httpプロバイダにインターセプタを追加することは可能です。

// register the interceptor as a service 
$provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) { 
    return { 
    // optional method 
    'request': function(config) { 
     // do something on success 
     return config || $q.when(config); 
    } 
} 

次に、インターセプタを登録します。

$httpProvider.interceptors.push('myHttpInterceptor'); 

あなただけの設定を編集する必要が:)

+4

これに注意して、テンプレートも傍受されます。 '/ api/my_template.html'をロードしたくない – Utopik

4

それは古い質問ですが、私はサービスコールのための相対パスを使用して

angular 
    .module('app') 
    .config(function ($httpProvider) { 
    $httpProvider.interceptors.push(apiInterceptor); 
    }); 

// api url prefix 
var API_URL = 'http://localhost:8080/'; 

function apiInterceptor ($q) { 
    return { 
    request: function (config) { 
     var url = config.url; 

     // ignore template requests 
     if (url.substr(url.length - 5) == '.html') { 
     return config || $q.when(config); 
     } 

     config.url = API_URL + config.url; 
     return config || $q.when(config); 
    } 
    } 
} 
関連する問題