raj raj - 1 month ago 19
AngularJS Question

Handling promises in Ionic project

I have a service which handles user authentication. The

auth
service that gets user details from database .

getUser(){
return this.storage.get('user').then( (user) => {
if (user){
this.user = user;
return user
}
}


And in the component I get the user like,

public user ;
ionViewDidLoad() {
this.auth.getUser().then( (user) => {
this.user = user;
})
.catch( (err) => console.log(err));
}


And in the html page I have
{{ user.uid }}
where uid is an attribute of the
user
object. But I get an error in the console,

Unhandled Promise rejection: Error in ./Home class Home - inline template:9:21 caused by: self.context.user is undefined ;

Zone: <root> ; Task: Promise.then ; Value: Object { _nativeError: Error, originalError: TypeError, context: Object, stack: "" } anonymous/_View_Home0.prototype.detectChangesInternal@Home.ngfactory.js:153:7


The user object will be resolved only after the promise get resolved. The user is not defined untill then. How can I resolve this issue. I do not want to use
async
with a promise return as I want to handle
error
catching in component.

Answer

You can use the elvis operator in your view, so if the user property is still null, Angular won't try to access the uid property.

{{ user?.uid }}

Comments