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

时间:2018-05-30 17:31:49

标签: angular firebase firebase-realtime-database angular5

我正在使用"身份验证服务"保持所有用户身份验证功能。当用户通过身份验证后,我会获得用户的ID,并从数据库表中获取相关记录,但是我无法获得" role"的值。领域。我在构造函数中使用的代码是:

@Query("UPDATE items SET saved=:saved WHERE NOT(id IN :itemsIds)") // ERROR??
abstract void method2(List<Long> itemsIds, boolean saved);

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未定义。

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

3 个答案:

答案 0 :(得分:1)

我添加了一些代码,让您了解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.roleget从其他组件访问set。无论你做了什么都是合适的。

您应该做的只是在未定义时才提取this.role

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

其他组件.ts

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

演示: 检查here以查看异步方法的工作原理

答案 1 :(得分:0)

您无法访问.subscribe()方法之外的变量,将其置于订阅

 this.currUser.subscribe(val => {
    this.role = val[0].role;
    console.log(this.role);
});

答案 2 :(得分:0)

我在用户服务中创建了以下功能:

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

然后我在组件中获得了用户ID:

get uid(): string {
    return this.authService.uid;
}
set uid(value: string) {
    this.authService.uid = value;
}

并在onNgInit()中调用该函数:

ngOnInit() {
    if (this.uid != undefined) {
        let uid = this.uid;

        this.userService.getUserRole(this.uid).subscribe(result => {
                    this.role = result.role;
        });
    }
}

最后我在html模板中使用了*ngIf="role == '<role>'