0

我使用 AngularJS 为 Rails 应用程序开发客户端,但我坚持使用authenticity_token。

这是我的服务的样子:

blog_app.factory('AuthenticityToken', ['$http', '$q',
  ($http, $q) ->
    () ->
      delay = $q.defer()
      $http.get('/authenticity_token').success(
        (data) ->
          delay.resolve(data.authenticity_token)
      ).error(
        ->
          delay.reject('Can\'t get authenticity_token')
      )

      return delay.promise
])


post_services.factory('Post', ['$resource',
  ($resource) ->
    $resource('/posts/:id', {id: '@id'},
    {
      query: {
        method: 'GET',
        params: {limit: 10, order: 'desk'},
        isArray: false
      }
    }
    )
])

如何在Post中注入和解析AuthenticityToken ,以便可以在Post的默认参数中使用真实性令牌?

相反,我只能为控制器解决它:

angular.module('posts', ['posts.services']).config(
  ['$routeProvider', ($routeProvider) ->
    $routeProvider
    .when('/posts', {
        templateUrl: '/pages/posts/',
        controller: 'ListCtrl',
        resolve: {
          authenticity_token: ['AuthenticityToken', (AuthenticityToken) ->
            AuthenticityToken()
          ]
        }
    })
  ]
)

然后显式传递给Post资源

4

1 回答 1

1
angular.module('posts', ['posts.services']).config(
  ['$routeProvider', '$httpProvider', ($routeProvider, $httpProvider) ->
    $httpProvider.defaults.headers.post['Content-Type'] = 'application/json'
    $httpProvider.defaults.headers.put['Content-Type'] = 'application/json'
    token = $("meta[name='csrf-token']").attr("content")
    $httpProvider.defaults.headers.post['X-CSRF-Token'] = token
    $httpProvider.defaults.headers.put['X-CSRF-Token'] = token
    $httpProvider.defaults.headers.common['X-CSRF-Token'] = token

    $routeProvider
    .when('/posts', {
        templateUrl: '/pages/posts/',
        controller: 'ListCtrl'
    })
  ]
)
于 2013-09-13T10:24:11.897 回答