Я добавил некоторый код, чтобы вы могли понять обратные вызовы наблюдаемого.Посмотрите на это.
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;
}
}
);
журнал 2 будет выполнен перед журналом 1, это связано с асинхронным поведением.Если вы думаете, что ваш код выполняется последовательно с номерами строк, то вы ошибаетесь.getUserRole
- асинхронный метод.
Вы также можете получить доступ к this.role
из других компонентов, используя get
или set
.Что бы вы ни делали, это уместно.
То, что вы должны делать, - это извлекать this.role
, только если оно не определено.
Во внешнем компоненте, к которому вы пытаетесь получить доступ this.role
,сначала проверьте undefined
, а затем получите доступ к нему.
некоторый другой компонент .ts
if(this.role != undefined){
let role = this.role
}
DEMO: проверьте здесь , чтобы увидеть, как работают асинхронные методы