如何在我的 angularjs 页面中从 RESTful API 访问服务? [英] How to access the services from RESTful API in my angularjs page?

查看:23
本文介绍了如何在我的 angularjs 页面中从 RESTful API 访问服务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 angularJS 很陌生.我正在搜索从 RESTful API 访问服务,但我没有任何想法.我该怎么做?

I am very new to angularJS. I am searching for accessing services from RESTful API, but I didn't get any idea. How can I do that?

推荐答案

Option 1: $http service

AngularJS 提供了 $http 服务正是您想要的:使用 JSON 向 Web 服务发送 AJAX 请求并从它们接收数据(这非常适合与 REST 服务对话).

Option 1: $http service

AngularJS provides the $http service that does exactly what you want: Sending AJAX requests to web services and receiving data from them, using JSON (which is perfectly for talking to REST services).

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

To give an example (taken from the AngularJS documentation and slightly adapted):

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

选项 2:$资源服务

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

Option 2: $resource service

Please note that there is also another service in AngularJS, the $resource service which provides access to REST services in a more high-level fashion (example again taken from AngularJS documentation):

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

选项 3:重新定义

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

Option 3: Restangular

Moreover, there are also third-party solutions, such as Restangular. See its documentation on how to use it. Basically, it's way more declarative and abstracts more of the details away from you.

这篇关于如何在我的 angularjs 页面中从 RESTful API 访问服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆