基本的AngularJS服务请求

时间:2017-01-19 03:46:11

标签: javascript angularjs api service

我正在尝试更改一个非常基本的示例应用程序,以便根据Springboot将应用程序的静态部分与服务器端分离。我想在nginx上运行应用程序的AngularJS静态部分,并对Springboot应用程序进行远程服务调用。

以下是应用程序的要点......

angular.module('blah', ['ent1', 'errors', 'status', 'info', 'ngRoute', 'ui.directives']).
config(function ($locationProvider, $routeProvider) {

    $routeProvider.when('/errors', {
        controller: 'ErrorsController',
        templateUrl: 'assets/templates/errors.html'
    });
    $routeProvider.otherwise({
        controller: 'MyController',
        templateUrl: 'assets/templates/albums.html'
    });
}
);

function MyController($scope, $modal, $location, $http, a, b, st) {


$scope.init = function() {
    console.log($location.host());  
--->        $location.host("http://somewhereelse:8080/");
    console.log($location.host());
    ....
};
}

为了便于阅读,删除了一些细节。

如您所见,我已将$location注入我的控制器,我认为这是我将更改主机的位置。但是,console.log之前和之后仍然显示“localhost”。

如何使用AngularJS对服务进行远程API调用?就像我说的那样,这可能是一个非常基本的问题。

1 个答案:

答案 0 :(得分:0)

希望您尝试从角度应用程序中进行一些API调用。为此,您可以使用angular $ http服务。

示例代码如下所示:

    // Simple GET request example:
$http({
  method: 'GET',
  url: '/someUrl'
}).then(function successCallback(response) {
    // this callback will be called asynchronously
    // when the response is available
  }, function errorCallback(response) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
  });

有关详细信息,请参阅官方文档:

https://docs.angularjs.org/api/ng/service/ $ HTTP