raj raj - 3 years ago 217
AngularJS Question

Handling promises in Ionic project

I have a service which handles user authentication. The

service that gets user details from database .

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
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
with a promise return as I want to handle
catching in component.

Answer Source

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 }}

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download