我添加了一些代码来让你理解 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
}
演示:
查看查看异步方法如何工作