我们如何使用与angularjs轨道线路在干燥的方式吗?(How can we use rails

2019-09-01 04:24发布

首先,我要说对不起,我的蹩脚的英语和断码...(多的话这里来自谷歌翻译...所以,恐怕我不能让自己清楚......所以,我粘贴所有代码...)

在轨道设置的路线是很容易的。 但是,当我们想将它弯曲成angurjs,就显得有点有点冗长......是否有此类型的职业中的任何“最佳实践”:

给予一定的轨道线路资源:

resources :users
resources :photos
...
resources :topics

如何做到这一点的角边?

这是我做(在咖啡脚本,期运用角度1.1.4):

使用Rails中的方式RESTful服务:

# angular/services/restful.js.coffee
# RESTful resource following Rails route's convention
# index:  GET  '/resource.json'
# save:   POST '/resource.json'
# get:    GET  '/resource/:id.json'
# update: PUT  '/resource/:id.json'
# edit:   GET  '/resource/:id/edit.json'
# new:    GET   just use get, id: 'new'
app.factory('RESTful', ['$resource',
  ($resource)->
    (resource_name) ->
      url = "/#{resource_name}/:id:format"
      defaults={format: '.json', id: '@id'}

      actions = {
        index:
          id: ''
          url: "/#{resource_name}:format"
          method: 'GET'
          isArray:false
        edit:
          url: "/#{resource_name}/:id/edit:format"
          method: 'GET'
        update:
          method: 'PUT'
        save:
          url: "/#{resource_name}:format"
          method: 'POST'
      }

      $resource url, defaults, actions
])

# index:  GET  '/parents/:parent_id/children.json'
# save:   POST '/parents/:parent_id/children.json'
# get:    GET  '/parents/:parent_id/children/:id.json'
# update: PUT  '/parents/:parent_id/children/:id.json'
# edit:   GET  '/parents/:parent_id/children/:id/edit.json'
# new:    GET   just use get, id: 'new'
app.factory('NESTful', ['$resource',
  ($resource)->
    (parents, children) ->
      # naive singularize
      parent = parents.replace(/s$/, '')
      url = "/#{parents}/:#{parent}_id/#{children}/:id:format"

      defaults={ format: '.json', id: '@id' }

      actions = {
        index:
          id: ''
          url: "/#{parents}/:#{parent}_id/#{children}:format"
          method: 'GET'
          isArray:false
        edit:
          url: "/#{parents}/:#{parent}_id/#{children}/:id/edit:format"
          method: 'GET'
        update:
          method: 'PUT'
        save:
          url: "/#{parents}/:#{parent}_id/#{children}:format"
          method: 'POST'
      }

      $resource url, defaults, actions
])

路线:

app.config(['$routeProvider', '$locationProvider', ($routeProvider, $locationProvider) ->
  $locationProvider.html5Mode(true)

  # general RESTful routes
  resource_list = ['users', 'photos', 'topics']
  for resource in resource_list
    # naive singularize
    singular = resource.replace(/s$/, "")
    captialize = singular.charAt(0).toUpperCase() + singular.slice(1)
    $routeProvider
      .when "/#{resource}",
          templateUrl: "/tp/#{resource}/index"
          controller: "#{captialize}IndexCtrl"
          resolve:
            index: ["#{captialize}Loader", (Loader)-> Loader('index')]
      .when "/#{resource}/new",
          templateUrl: "/tp/#{resource}/edit"
          controller: "#{captialize}NewCtrl"
          resolve:
            resource: ["#{captialize}Loader", (Loader)-> Loader('new')]
      .when "/#{resource}/:id",
          templateUrl: "/tp/#{resource}/show"
          controller: "#{captialize}ShowCtrl"
          resolve:
            resource: ["#{captialize}Loader", (Loader)-> Loader('show')]
      .when "/#{resource}/:id/edit",
          templateUrl: "/tp/#{resource}/edit"
          controller: "#{captialize}EditCtrl"
          resolve:
            resource: ["#{captialize}Loader", (Loader)-> Loader('edit')]

  # special routes
  $routeProvider
    .when '/',
        templateUrl: '/tp/pages/home'
        controller: 'PageCtrl'

    .otherwise({redirectTo: '/'})
])

控制器应该是超级干净,然后我们可以专注于商务大

app.controller 'UserShowCtrl', ['$scope', 'resource'
  ($scope, resource)->
    $scope.user = resource.user
]
app.controller 'UserIndexCtrl', ['$scope', 'index',
  ($scope, index) ->
    $scope.users = index.resource.users
    $scope.total_pages = index.pages.total_pages
    $scope.currentPage = index.pages.current_page

    getPage = (page)->
      index.resource.$index
        page: page
        (resource, headers)->
          $scope.users = resource.users

    $scope.$watch 'currentPage', (newval)->
      getPage(newval)
]

问题是,在装载机的决心OBJ:

app.factory('UserLoader', ['RESTful', '$route', '$q',
  (RESTful, $route, $q) ->
    (action)->
      model = 'users'
      delay = $q.defer()
      fetcher = RESTful(model)
      switch action
        when 'index'
          fetcher.index
            page: $route.current.params.page
            (resource, headers)->
              delay.resolve
                resource: resource
                pages: JSON.parse(headers('X-Pagination'))
            (resource)->
              delay.reject "Unable to fetch #{model} index"
        when 'show'
          fetcher.get
            id: $route.current.params.id
            (resource)->
              delay.resolve(resource)
            (resource)->
              delay.reject "Unable to fetch #{model} #{$route.current.params.id}"
        when 'edit'
          fetcher.edit
            id: $route.current.params.id
            (resource)->
              delay.resolve(resource)
            (resource)->
              delay.reject "Unable to fetch #{model} #{$route.current.params.id} edit"
        when 'new'
          fetcher.get
            id: 'new'
            (resource)->
              delay.resolve(resource)
            (resource)->
              delay.reject "Unable to fetch #{model} new"

      return delay.promise
])

这里有两个问题:第一个问题是,我必须复制粘贴&&上面加载程序代码,然后GSUB(“用户”,“照片”),等等......(只要改变其实2个字,但我讨厌副本&&贴..)我试图在for循环中移动它没有工作,我想不通为什么...另一个问题是如何建立嵌套的资源,在干燥的方式

最后,感谢您的耐心,我会再次说声抱歉......但任何解决方案,建议或最佳做法? 我是不是做错了?

Answer 1:

除此之外,你的问题的描述是非常复杂(大量代码),我想你错过了REST API的概念点。

您正在使用的客户端路由混合Rails的后端资源(和它的路由)。 这是错误恕我直言。 您的前端应用程序的路线不应该跳(阴影)通过REST路线。 如果您在获取users资源(例如GET /users/5.json )你不应该浏览您的客户端/tp/users/show 。 你的休息和客户端路线是两个独立的,独立的抽象。

您的客户端的路线应该是这样的

/
/userprofile
/dashboard
/articles/2013?page=4

和你的控制器坐在这些路由应该用你的资源服务来从REST API这样所需的数据:

angular.module('myApp').controller 'UserProfileController', ($scope, userResource) ->
  $scope.user = userResource.query({id: SOME_ID})

angular.module('myApp.resources').factory 'userResource', ($resource) ->
  params = {
    id: '@id'
    subItem: '@subItem'
    subItemId: '@subItemId'
  }

  actions = {
    query: {
      method: 'GET'
      params: {}
      isArray: true
    }
    ban: {
      method: 'POST'
      params: {banned: true}
    }
  }

  return $resource('/api-1.0/users/:id/:subItem/:subItemId', params, actions)


Answer 2:

嗯,我弄清楚为什么决心不能按预期工作装载机......最关键的是,一个angularjs服务是sigleton。 它不工作,因为我把循环服务定义中的第一个版本...

对于排序,这个工程:

angular.forEach [
  ['profile', 'profile']
  ['user', 'users']
  ['avatar', 'avatars']
],
(resouce_definition)->
  resource = resouce_definition[1]
  singular = resouce_definition[0]
  captialize = singular.charAt(0).toUpperCase() + singular.slice(1)
  app.factory("#{captialize}Loader", [
    'RESTful', '$route', '$q'
    (RESTful, $route, $q)->
      (action)->
        delay = $q.defer()
        id = $route.current.params.id
        fetcher = RESTful(resource)
        switch action
          when 'index'
            fetcher.index
              page: $route.current.params.page
              (response, headers)->
                delay.resolve
                  resource: response
                  pages: JSON.parse(headers('X-Pagination'))
              (response)->
                delay.reject "Unable to fetch #{resource} index"
          when 'show'
            fetcher.get
              id: id
              (response)->
                delay.resolve(response)
              (response)->
                delay.reject "Unable to fetch #{resource} #{id}"
          when 'edit'
            fetcher.edit
              id: id
              (response)->
                delay.resolve(response)
              (response)->
                delay.reject "Unable to fetch #{resource} #{id}"
          when 'new'
            fetcher.get
              id: 'new'
              (response)->
                delay.resolve(response)
              (response)->
                delay.reject "Unable to fetch #{resource} new"

        return delay.promise
  ])


Answer 3:

我尽量避免像复杂的服务:“/父母/:PARENT_ID /儿童/:身份证”
我在两个服务分开处理:
/父母/:PARENT_ID /儿童。 对于GET(列表)和(在内容ID)的讯息,接着我对PUT /儿童/ ID,删除和单GET



文章来源: How can we use rails routes with angularjs in a DRY way?