【问题标题】:Can't get data from JSON object from firebase无法从 firebase 的 JSON 对象获取数据
【发布时间】:2018-06-02 22:37:06
【问题描述】:

我想从我的 firebase 数据库请求的 JSON 对象中获取登录用户的“userRole”。所以我尝试了以下代码:

ionViewWillLoad(){
    this.afAuth.authState.subscribe(user => {
        this.ref = user.uid;
        this.userService.getUserById(this.ref).subscribe(data => {
            this.data = data
            console.log(this.data);
        })
    });
}

我从数据库中获取的文件如下所示:

0:{$value: "admin@gmail.com", $key: "email", $exists: ƒ}
1:{$value: "password", $key: "password", $exists: ƒ}
2:{$value: 1, $key: "userRole", $exists: ƒ}
3:{$value: "", $key: "worksFor", $exists: ƒ}

如何从这个 JSON 对象访问“userRole”?我尝试了“data.userRole”、“data[2].$value”,但这些都不起作用。

以下是向数据库添加新用户的代码:

getUserById(id){
    return this.afd.list('/users/' + id);
}

register(user){
    return this.afAuth.auth.createUserWithEmailAndPassword(user.email, user.password).then(data => {
        this.afd.object('/users/' + data.uid).update(user);
    });
}

我向数据库添加数据的方式有问题吗?

谢谢!

【问题讨论】:

  • 我认为您的数据库中有 2 个信息 - 身份验证表和 /users/ 实时数据库“表”,那么您要访问哪一个?
  • 我想从 /user/ 表中获取数据,基于当前登录的用户@Makah
  • 如果你正在接收数据,你可以尝试通过数据访问它[“userRole”]
  • @ayudh 感谢您的帮助。

标签: javascript firebase-realtime-database firebase-authentication angularfire2


【解决方案1】:

Firebase 有多种产品,我认为您需要使用其中两种。 Authentication 控制用户身份验证,Realtime database 将其他信息保存为地址、电话和与您的项目相关的其他数据。

就我而言,我更喜欢将用户信息包装在服务中 - my example。片段:

import { AngularFireDatabase } from 'angularfire2/database';
import { AngularFireAuth } from 'angularfire2/auth';

constructor(public afAuth: AngularFireAuth, private db: AngularFireDatabase) { }

load() {
    let promise = new Promise((resolve, reject) => {
        this.afAuth.authState.subscribe((auth) => {
            this.authState = auth
            resolve(true);
        },
            err => reject(err)
        );
    });

    return promise;
}

get userID(): string {
    return this.authenticated ? this.authState.uid : '';
}

retrieveUser(): any {
    if(this.authenticated === undefined){
        console.log('You need to authenticate first.');
        return null;
    }

    this.user = this.db.object('/users/'+ this.userID)
                    .valueChanges()
                    .publishReplay(1)
                    .refCount();


    return this.user;
}

我是这样使用的:

this.authService.retrieveUser().subscribe(user => {
  this.user = user;  
});

【讨论】:

  • 谢谢,它就像魔术一样工作。错误是我正在添加一个对象并从数据库中请求一个列表。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-14
  • 1970-01-01
  • 2017-10-04
  • 1970-01-01
  • 2018-06-18
相关资源
最近更新 更多