How to call method from app.component?

Hello!

I’m developing ionic/angular/cordova app. And I have some issues with stucture.

So:
I have side menu with username and user image, and method, that get this info:

export class AppComponent {
    public appPages = [
        {
            title: 'test',
            url: '/test'
        },
    ];

    name: any;
    avatar: any;
    surname: any;

    constructor(
        ...
        private platform: Platform,
        private authService: AuthService,
        ...
    ) {
        this.initializeApp();
    }

    initializeApp() {
        this.platform.ready().then(() => {
            ...
            this.getUser()
        });
    }

    getUser() {
       this.authService.user().subscribe(res => {
                this.avatar = res.avatar
                this.name = res.firstname
                this.surname = res.lastname
            })
    }
}

So when user is logged, I can get user info from authService, with token.

But!
When, I’m trying to get this info without token (user not logged in), I get error.

So, I need to add some check:

if(this.authService.isLoggedIn) {
            this.authService.user().subscribe(res => {
                this.avatar = res.avatar
                this.name = res.firstname
                this.surname = res.lastname
            })
        }

And authService.isLoggedIn is boolean:

isLoggedIn = false;

So, first the problem is:

When I’m adding check, function is not working. Why?

And the second problem:
When user logging in, I need to call this method. How can I do it?
Maybe there is normal way to use app.component?

This is an extremely self-aware and insightful assessment of the situation. It’s going to be uncomfortable, but you need to learn to think backwards.

One way of dividing methods in Ionic apps is into procedures (which do stuff) and functions (which return values). The two shouldn’t be mixed: procedures should always return void and functions should never modify anything outside themselves. Obviously, those aren’t 100% hard-and-fast rules, but the more I follow them, the happier I find myself.

Functions can further be subdivided into those that involve any asynchronous sources and those that don’t. If a function involves even one asynchronous source, its return value must be a future (Promise or Observable). It can’t return a concrete type.

So you’ve seemingly written getUser as a procedure (despite the name). If you change it to be a function, then it has to return an Observable<User>, which designs away your problem by allowing the Observable<User> that it does return to emit new Users when users login and logout. However, you have to eliminate all assignments outside getUser from within getUser, and you also have to move subscription out of getUser and into its callers.