0

我收到以下错误:TypeError: Object [object global] has no method 'setApiToken'

angular.module("userService", ["restangular", "angular-cache"]).factory "userService", (Restangular, $angularCacheFactory) ->

 setCurrentUserId: (value) ->
     # Code here...

 login: (user, callback) ->
  # FOR TESTING PURPOSES, I DON'T GET AN ERROR HERE
  @setApiToken(1)
  Restangular.all("sessions").post(user).then (returnVal) ->
    returnJson = angular.fromJson(returnVal)

    if returnJson.success is true
      # I GET AN ERROR HERE ############################################
      @setApiToken(returnJson.data.authToken)
      returnJson.id
    else
      ""
4

1 回答 1

3

@SLaks 是对的。您需要一个粗箭头来保持this回调到then(). 此外,您不需要解析 JSON 响应,应该由Restangular.

angular.module("userService", ["restangular", "angular-cache"]).factory "userService", (Restangular, $angularCacheFactory) ->

 setCurrentUserId: (value) ->
     # Code here...

 login: (user, callback) ->
  # FOR TESTING PURPOSES, I DON'T GET AN ERROR HERE
  @setApiToken(1)
  Restangular.all("sessions").post(user).then (returnVal) =>
    returnJson = angular.fromJson(returnVal)

    if returnJson.success is true
      # I GET AN ERROR HERE ############################################
      @setApiToken(returnJson.data.authToken)
      returnJson.id
    else
      ""
于 2013-10-11T18:54:26.667 回答