简体   繁体   中英

Managing REST endpoints in Angular JS?

是否有最佳实践在Angular JS的一个位置存储和管理应用程序的所有REST端点?

In AngularJS

app.value('config', {
  "baseUrl": "http://www.some.url"
});

and access it with

config.baseUrl + "/fetchAll.json"

Do not forget to inject dependency config .

Regards.

A Generic One which I am comfortable using:

angular.module('myApp').factory('ConnectionService', function ($http, $log) {
    var connectionurl = 'http://localhost:8000/Services.svc/';
    return {
        connectionurl: connectionurl,

        getData:function(successCallBack){
             $http({
                   method: 'GET',
        /********HERE COMES YOUR REST WebGet or WebInvoke URI************/
                   url: connectionurl+ 'methodname'
             })
             .success(function (data, status, headers, config) {
                successCallBack(data);
           })
            .error(function (data, status, headers, config) {
                $log.warn(data, status, headers, config);
            })
          }
     });

You can use this ConnectionService in your controller as

angular.module('myApp').controller('SampleController',
          function ($scope,ConnectionService){
                    ConnectionService.getData(function(response){
                    $scope.object=response;
          });
}

You can store them as constants outside application, according to this great document .

You can store such config as

env.js

(function (window) {
    window.__env = window.__env || {};

    // Login page address
    window.__env.loginUrl = 'http://website/login';

}(this));

then assign it as a constant in your main module

app.js

angular.module('yourmodule', [])
    .constant('__env', __env)

and then you can inject in in your service

loginData.$inject = ['$http', '__env'];

Such configuration works best for me, is easy to manage and change depending on environment, without rebuilding application. Just assigning constant doesn't have such advantage.

您应该尝试将$ resource用于所有REST定义。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM