javascript 处理 CRUD 资源的 AngularJS“方式”是什么

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18003092/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 10:25:14  来源:igfitidea点击:

What's the AngularJS "way" of handling a CRUD resource

javascriptruby-on-railsangularjsruby-on-rails-4

提问by randombits

I am interested in moving a lot of my client's "logic" away from Rails routing to AngularJS. I have slight confusion in one topic and that is linking. Now, I do understand there's more than one way to handle this, but what is the common practice in the AngularJS community for handling URLs on handling CRUD for resources. Imagine in the case of an athlete we have a URL such as the following to list all athletes:

我有兴趣将我客户的很多“逻辑”从 Rails 路由转移到 AngularJS。我对一个主题有点困惑,那就是链接。现在,我知道有不止一种方法可以处理这个问题,但是 AngularJS 社区中处理 CRUD 资源的 URL 的常见做法是什么。想象一下,对于一名运动员,我们有一个如下所示的 URL 来列出所有运动员:

http://example.com/athletes

http://example.com/athletes

To view an individual athlete:

查看单个运动员:

http://example.com/athletes/1

http://example.com/athletes/1

To edit an individual athlete:

要编辑单个运动员:

http://example.com/athletes/1/edit

http://example.com/athletes/1/edit

To create a new athlete:

要创建新运动员:

http://example.com/athletes/new

http://example.com/athletes/new

In AngularJS, is it common practice to reroute to similar URLs to create/edit/update? Would you just have one URL handle all of the CRUD type actions in one interface and never change the URL? If you were to change the URL, does that get handled via ng-click and in the click event would you use the $locationobject to change URLs? I'd love to be able to read up on common practices such as these, but having a difficult time in finding more recent literature on it in an AngularJS context.

在 AngularJS 中,重新路由到类似的 URL 以创建/编辑/更新是常见的做法吗?您是否会只让一个 URL 在一个界面中处理所有 CRUD 类型的操作并且永远不更改 URL?如果您要更改 URL,是否会通过 ng-click 处理?在 click 事件中,您是否会使用该$location对象来更改 URL?我很想能够阅读这些常见的实践,但是很难在 AngularJS 上下文中找到更多关于它的最新文献。

** NOTE **

** 笔记 **

I totally get that you can still use RESTful routes to the backend in order to interact with server-side resources. My question is, what is the style that is recommended to use when updating URLs on the client-side. Are you using AngularJS to do that for each of the CRUD operations?

我完全明白您仍然可以使用 RESTful 路由到后端,以便与服务器端资源进行交互。我的问题是,在客户端更新 URL 时建议使用什么样式。您是否使用 AngularJS 为每个 CRUD 操作执行此操作?

回答by Derek Hinchliffe

I would definitely recommend separate URLs for each operation (to enable direct linking). The ones you suggest look fine.

我肯定会为每个操作推荐单独的 URL(以启用直接链接)。你推荐的那些看起来不错。

In AngularJS you can use the $routeservice in combination with the ngViewdirective to load the appropriate template for each operation and handle the browser location and history mechanics for you.

在 AngularJS 中,您可以将$route服务与ngView指令结合使用,为每个操作加载适当的模板,并为您处理浏览器位置和历史记录机制。

Step 7 of the AngularJS tutorialgives an example of using Views, Routing and Templates the way I describe here. The following is a simplified version for your example:

AngularJS 教程的第 7 步给出了一个使用视图、路由和模板的例子,我在这里描述的方式。以下是您示例的简化版本:

Define the routes

定义路由

In your main application script (e.g. app.js):

在您的主应用程序脚本(例如app.js)中:

angular.module('AthletesApp', []).
  config(['$routeProvider', function($routeProvider, $locationProvider) {
  // Configure routes
  $routeProvider.
      when('/athletes', {templateUrl: 'partials/athletes-list.html',   controller: AthleteListCtrl}).
      when('/athletes/:athleteId', {templateUrl: 'partials/athlete-detail.html', controller: AthleteDetailCtrl}).
      when('/athletes/:athleteId/edit', {templateUrl: 'partials/athlete-edit.html', controller: AthleteEditCtrl}).
      when('/athletes/:athleteId/new', {templateUrl: 'partials/athlete-new.html', controller: AthleteNewCtrl}).
      otherwise({redirectTo: '/athletes'});
  // Enable 'HTML5 History API' mode for URLs.
  // Note this requires URL Rewriting on the server-side. Leave this
  // out to just use hash URLs `/#/athletes/1/edit`
  $locationProvider.html5Mode(true);
}]);

We also enable 'HTML Mode' for URLs, see note below.

我们还为 URL 启用了“HTML 模式”,请参阅下面的注释。

2. Add an ngViewdirective to your HTML

2.ngView在 HTML 中添加指令

In your main index.htmlyou specify where the selected partial template will go in the overall layout:

在您的主index.html 中,您指定所选部分模板在整体布局中的位置:

<!doctype html>
<html ng-app="AthletesApp">
...
   <!-- Somewhere within the <body> tag: -->
   <div ng-view></div>
...
</html>

3. Create templates and controllers

3. 创建模板和控制器

Then you create the partial view templates and matching controllers for each of the operations. E.g. for the athlete detail view:

然后为每个操作创建局部视图模板和匹配的控制器。例如对于运动员详细信息视图:

partials/athelete-detail.html:

部分/athlete-detail.html:

<div>
    ... Athete detail view here
</div>

athleteDetailCtrl.js:

运动员详细信息Ctrl.js:

angular.module('AthletesApp').controller('AtheleteDetailCtrl',
    function($scope, $routeParams) {
        $scope.athleteId = $routeParams.athleteId;
        // Load the athlete (e.g. using $resource) and add it
        // to the scope.
    }

You get access to the route parameter (defined using :athleteIdin the route config) via the $routeParamsservice.

您可以:athleteId通过该$routeParams服务访问路由参数(在路由配置中定义)。

4. Add links

4. 添加链接

The final step is to actually have links and buttons in your HTML to get to the different views. Just use standard HTML and specify the URL such as:

最后一步是在 HTML 中实际包含链接和按钮以访问不同的视图。只需使用标准 HTML 并指定 URL,例如:

<a href="/athletes/{{athleteId}}/edit">Edit</a>

Note: Standard vs Hash URLs

注意:标准 URL 与哈希 URL

In older browsers that don't support the HTML5 History API your URLs would look more like http://example.com/#/athletesand http://example.com/#/athletes/1.

在不支持 HTML5 History API 的旧浏览器中,您的 URL 看起来更像http://example.com/#/athleteshttp://example.com/#/athletes/1

The $locationservice (used automatically by $route) can handle this for you, so you get nice clean URLs in modern browsers and fallback to hash URLs in older browsers. You still specify your links as above and $locationwill handle rewriting them for older clients. The only additional requirement is that you configure URL Rewriting on the server side so that all URLs are rewritten to your app's main index.html. See the AngularJS $location Guidefor more details.

$location服务(由 自动使用$route)可以为您处理此问题,因此您可以在现代浏览器中获得漂亮干净的 URL,并在旧浏览器中回退到散列 URL。您仍然如上所述指定您的链接,$location并将处理为旧客户重写它们。唯一的附加要求是您在服务器端配置 URL 重写,以便将所有 URL 重写到应用程序的主 index.html。有关更多详细信息,请参阅AngularJS $location 指南

回答by holographic-principle

The angular way is the restful way:

有角度的方式是宁静的方式:

GET all http://example.com/athletes
GET one http://example.com/athletes/1
POST new http://example.com/athletes
PUT edit http://example.com/athletes/1
DELETE remove http://example.com/athletes/1

Note that $resourcealso expects a few other things, like resource URLs not ending with a slash, PUT requests returning the updated resource, etc.

请注意,$resource还需要其他一些东西,例如不以斜杠结尾的资源 URL、返回更新资源的 PUT 请求等。

If your API doesn't meet these criteria, or you simply need more flexibility, you can build your own $resource-like CRUD service based on the lower-level $httpservice. One way of doing the latter is explained here

如果您的 API 不符合这些标准,或者您只是需要更大的灵活性,您可以基于较低级别的$http服务构建您自己的 $resource-like CRUD服务。此处解释了执行后者的一种方法

回答by Golo Roden

Option 1: $http service

选项 1:$http 服务

AngularJS provides the $httpservicethat 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 提供的$http服务完全符合您的要求:使用 JSON(非常适合与 REST 服务对话)向 Web 服务发送 AJAX 请求并从它们接收数据。

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

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

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

Option 2: $resource service

选项2:$资源服务

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

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

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

Option 3: Restangular

选项 3:重新排列

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

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

回答by Tadeusz Wójcik

In AngularJS you can definitely use RESTful server side data sources, there is build in service called $resource.

在 AngularJS 中,你绝对可以使用 RESTful 服务器端数据源,有一个名为$resource 的内置服务。

Alternatively you can also use restangularwhich has additional features over $resource.

或者,您也可以使用具有超过 $resource 的附加功能的restangular

If you want to have full control you can always use $httpservice which is low level angular component for interacting with http.

如果你想完全控制你总是可以使用$http服务,它是与 http 交互的低级角度组件。

回答by Games Brainiac

Simply implement something that is RESTful, that is the angularJS way. If you have no idea what RESTful is or, know a little and want to know a lot more, then I would recommend that you read thisarticle.

只需实现 RESTful 的东西,那就是 angularJS 方式。如果你不知道 RESTful 是什么,或者,知道一点,想知道更多,那么我建议你阅读这篇文章。

Basically, REST is what is understood to be, an intuitive implementation of WEB URIs, it also makes use of all HTTP verbs, their correct use actually. REST is an approach, and architecture to building web apps.

基本上,REST 被理解为 WEB URI 的直观实现,它还利用了所有 HTTP 动词,它们实际上是正确使用的。REST 是一种构建 Web 应用程序的方法和架构。