ani*_*CSE 88 rest restful-url angularjs angularjs-service
我对angularJS很新.我正在寻找从RESTful API访问服务,但我没有任何想法.我怎样才能做到这一点?
Gol*_*den 145
AngularJS提供的$http服务完全符合您的要求:使用JSON(非常适合与REST服务交谈)向Web服务发送AJAX请求并从中接收数据.
举一个例子(取自AngularJS文档并略微调整):
$http({ method: 'GET', url: '/foo' }).
success(function (data, status, headers, config) {
// ...
}).
error(function (data, status, headers, config) {
// ...
});
Run Code Online (Sandbox Code Playgroud)
请注意,AngularJS中还有另一项服务,该$resource服务以更高级的方式提供对REST服务的访问(例如,再次从AngularJS文档中获取):
var Users = $resource('/user/:userId', { userId: '@id' });
var user = Users.get({ userId: 123 }, function () {
user.abc = true;
user.$save();
});
Run Code Online (Sandbox Code Playgroud)
此外,还有第三方解决方案,如Restangular.请参阅有关如何使用它的文档.基本上,它更具说明性,并将更多细节抽象出来.
Ale*_*øld 13
在$ HTTP服务可以用于一般用途的AJAX.如果你有一个合适的RESTful API,你应该看看ngResource.
您还可以查看Restangular,它是第三方库,可以轻松处理REST API.
Mik*_*ill 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>
Run Code Online (Sandbox Code Playgroud)
接下来,您需要在HTML文件中添加一些代码,以强制Angular调用'GET'Web服务:
// 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'];
}]);
Run Code Online (Sandbox Code Playgroud)
一旦你有了这些修复,实际上调用RESTful API真的很简单.
function YourAngularController($scope, $http)
{
$http.get('http://www.iNorthwind.com/Service1.svc/getAllCustomers')
.success(function (data) {
//
// Do something with the data !
//
});
}
Run Code Online (Sandbox Code Playgroud)
您可以在此网页上找到这些步骤的非常清晰的演练:
祝好运 !
麦克风
只是为了扩展$http(快捷方法):http://docs.angularjs.org/api/ng.$http
//来自页面的片段
$http.get('/someUrl').success(successCallback);
$http.post('/someUrl', data).success(successCallback);
Run Code Online (Sandbox Code Playgroud)
//可用的快捷方法
$http.get
$http.head
$http.post
$http.put
$http.delete
$http.jsonp
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
128376 次 |
| 最近记录: |