根据角度中的用户ID从数据库获取用户角色

2024-01-09

我正在使用“身份验证服务”来保留所有用户身份验证功能。当用户通过身份验证时,我获取用户的 ID 并从数据库表中获取相关记录,但无法获取“角色”字段的值。我在构造函数中使用的代码是这样的:

constructor(
    private _firebaseAuth: AngularFireAuth,
    private db: AngularFireDatabase,
    private router: Router) {
    this.user = _firebaseAuth.authState;

    this.user.subscribe(
        (user) => {
            if (user) {
                this.userDetails = user;

                this.userEmail = this.userDetails.email;
                this.uid = this.userDetails.uid;

                this.getUserRole(this.uid).subscribe(result => {
                    this.role = result.role;
                    console.log('role >>>>>>>>>>>>>', this.role);
                });

                console.log('uid >>>>>>>>>>>>>', this.uid);
                console.log('role >>>>>>>>>>>>>', this.role);
            }
            else {
                this.userDetails = null;
            }
        }
    );
}

getUserRole(userId: string): Observable<any> {
    return this.db.list('users', ref => ref.orderByChild('uid').equalTo(this.uid)).valueChanges()
        .map(result => result[0]);
}

this.uid有正确的值,但是this.role未定义。

我认为对数据库表的调用是异步的问题。 我怎样才能得到这个值?


我添加了一些代码来让你理解 observable 的回调。看看它。

this.currUser.subscribe(
        (val) => {
            // This is called as success callback
            this.role = val[0].role;
           // perform task using this.role. You should be writing your code here.
        },
        (error) => {
                // This is called as error callback, It will be executed if any erorrs were thrown from `currUser()`
                // log if there are any errors here
        },
        () => {
            // This is called as complete block
            // This will be executed after success callback or the error callback.
        }
);

更新 :

this.user.subscribe(
    (user) => {
        if (user) {
            this.userDetails = user;

            this.userEmail = this.userDetails.email;
            this.uid = this.userDetails.uid;

            this.getUserRole(this.uid).subscribe(result => {
                this.role = result.role;
                console.log('role >>>>>>>>>>>>>', this.role);       // print log 1
            });

            // log 2 will be executed before log 1 this is due to asynchronous behaviour
            console.log('role >>>>>>>>>>>>>', this.role);           // print log 2
        }
        else {
            this.userDetails = null;
        }
    }
);

log 2 将在 log 1 之前执行,这是由于异步行为。如果您认为代码按行号顺序执行,那么您就错了。getUserRole是异步方法。

您可以访问this.role从其他组件以及使用get or set。无论你做什么都是适当的。

你应该做的是获取this.role仅当它不是未定义时。

在您尝试访问的外部组件中this.role, 检查undefined首先然后访问它。

其他一些组件 .ts

if(this.role != undefined){
 let role = this.role
}

演示: 查看查看异步方法如何工作

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

根据角度中的用户ID从数据库获取用户角色 的相关文章

随机推荐