简体   繁体   English

AngularJS通过JSON API从用户获取相关数据

[英]AngularJS get related data from user through JSON API

I'm using Ionic framework, but question is about AngularJS. 我正在使用Ionic框架,但问题是关于AngularJS。 I have written json api on ruby on rails. 我在轨道上写了红宝石上的json api。 For authentication I choose ng-token-auth + devise-token-auth . 对于身份验证,我选择ng-token-auth + devise-token-auth

User json: 用户json:

{
  "data": {
    "id": "1",
    "type": "users",
    "attributes": {
      "name": "User1",
      "email": "email@email.com",
      "current-sign-in-at": "..",
      "last-sign-in-at": "..",
      "created-at": ".."
    },
    "relationships": {
      "friends": {
        "data": [
              {
                  "id": "2",
                  "type": "users"
              }
         ]
       }
    }
  },
  "included": [
    {
      "id": "2",
      "type": "users",
      "attributes": {
        "name": "User2",
        "email": "user@user.com",
        "current-sign-in-at": "..",
        "last-sign-in-at": "..",
        "created-at": ".."
      },
      "relationships": {
        "friends": {
             "data": [ ]
         }
      }
    }
  ]
}

My serializer for user: 我的用户序列化器:

class UserSerializer < ActiveModel::Serializer
  attributes :id, :name, :email,:current_sign_in_at,
              :last_sign_in_at, :created_at
  has_many :friends, through: :friendships
end

Current user object as response: 当前用户对象作为响应:

{"success":true,"data":{"id":1,"provider":"email","uid":"0a56bb6b-dc72-4ef3-906e-1c17cb2fef46","name"
:"User1","nickname":null,"image":null,"email":"email@email.com"}}

There is my problem, I can't reach user relationship information. 有我的问题,我无法达到用户关系信息。

I don't know why, but object name in my view is user (not current_user) and don't have access for it in my controllers. 我不知道为什么,但我的视图中的对象名称是user(不是current_user),并且在我的控制器中没有访问权限。 Question is how can I have some additional information from this object and how to provide current user object access for my controllers. 问题是我如何从该对象获得一些额外信息以及如何为我的控制器提供当前用户对象访问。

I figured it out, so the answer is really simple. 我想通了,所以答案很简单。 ng-token-auth provide $rootScope.user as the current user and it can be used in controllers. ng-token-auth提供$rootScope.user作为当前用户,它可以在控制器中使用。 But I still don't know how to provide related data to user object, fortunately found workaround for my needs. 但我仍然不知道如何向用户对象提供相关数据,幸运的是找到了解决方案以满足我的需求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM