89

我对 angularJS 很陌生。我正在搜索从 RESTful API 访问服务,但我不知道。我怎样才能做到这一点?

4

5 回答 5

145

选项 1:$http 服务

AngularJS 提供的$http服务完全符合您的要求:使用 JSON(非常适合与 REST 服务对话)向 Web 服务发送 AJAX 请求并从它们接收数据。

举个例子(取自 AngularJS 文档并稍作修改):

$http({ method: 'GET', url: '/foo' }).
  success(function (data, status, headers, config) {
    // ...
  }).
  error(function (data, status, headers, config) {
    // ...
  });

选项 2:$resource 服务

请注意,AngularJS 中还有另一个服务,该$resource服务以更高级的方式提供对 REST 服务的访问(示例再次取自 AngularJS 文档):

var Users = $resource('/user/:userId', { userId: '@id' });
var user = Users.get({ userId: 123 }, function () {
  user.abc = true;
  user.$save();
});

选项 3:Restangular

此外,还有第三方解决方案,例如Restangular。请参阅其文档以了解如何使用它。基本上,它更具声明性,并从您那里抽象出更多细节。

于 2013-05-06T07:35:18.410 回答
13

$http服务可用于通用 AJAX。如果你有一个合适的 RESTful API,你应该看看ngResource

您还可以查看Restangular,这是一个可以轻松处理 REST API 的第三方库。

于 2013-05-06T07:36:10.353 回答
10

欢迎来到 Angular 的精彩世界!!

我对 angularJS 很陌生。我正在搜索从 RESTful API 访问服务,但我不知道。请帮我这样做。谢谢

如果您当前正在使用“GET”服务,那么编写您的第一个 Angular 脚本有两个(非常大的)障碍。

首先,您的服务必须实现“Access-Control-Allow-Origin”属性,否则当从 Web 浏览器调用时,服务会很有效,但从 Angular 调用时会失败。

因此,您需要在web.config文件中添加几行:

<configuration>
  ... 
  <system.webServer>
    <httpErrors errorMode="Detailed"/>
    <validation validateIntegratedModeConfiguration="false"/>
    <!-- We need the following 6 lines, to let AngularJS call our REST web services -->
    <httpProtocol>
        <customHeaders>
            <add name="Access-Control-Allow-Origin" value="*"/>
            <add name="Access-Control-Allow-Headers" value="Content-Type"/>
        </customHeaders>
    </httpProtocol>
  </system.webServer>
  ... 
</configuration>

接下来,您需要在 HTML 文件中添加一些代码,以强制 Angular 调用“GET”网络服务:

// Make sure AngularJS calls our WCF Service as a "GET", rather than as an "OPTION"
var myApp = angular.module('myApp', []);
myApp.config(['$httpProvider', function ($httpProvider) {
    $httpProvider.defaults.useXDomain = true;
    delete $httpProvider.defaults.headers.common['X-Requested-With'];
}]);

一旦你有了这些修复,实际上调用一个 RESTful API 真的很简单。

function YourAngularController($scope, $http) 
{
    $http.get('http://www.iNorthwind.com/Service1.svc/getAllCustomers')
        .success(function (data) {
        //  
        //  Do something with the data !
        //  
    });
}

您可以在此网页上找到这些步骤的非常清晰的演练:

使用 Angular 和 JSON 数据

祝你好运 !

麦克风

于 2014-01-21T12:45:35.490 回答
7

只是在这里扩展$http(快捷方式):http: //docs.angularjs.org/api/ng.$http

//来自页面的片段

$http.get('/someUrl').success(successCallback);
$http.post('/someUrl', data).success(successCallback);

//可用的快捷方式

$http.get
$http.head
$http.post
$http.put
$http.delete
$http.jsonp
于 2013-08-17T20:31:52.927 回答
0

例如,您的 json 看起来像这样: {"id":1,"content":"Hello, World!"}

您可以像这样通过 angularjs 访问它:

angular.module('app', [])
    .controller('myApp', function($scope, $http) {
        $http.get('http://yourapp/api').
            then(function(response) {
                $scope.datafromapi = response.data;
            });
    });

然后在你的 html 上你会这样做:

<!doctype html>
<html ng-app="myApp">
    <head>
        <title>Hello AngularJS</title>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js"></script>
        <script src="hello.js"></script>
    </head>

    <body>
        <div ng-controller="myApp">
            <p>The ID is {{datafromapi.id}}</p>
            <p>The content is {{datafromapi.content}}</p>
        </div>
    </body>
</html>

如果您不想下载它们,这将调用 angularjs 的 CDN。

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js"></script>
<script src="hello.js"></script>

希望这可以帮助。

于 2017-12-18T17:34:24.707 回答