0

I have a component with ngOnInit() and a login() method.

How can I update the component and execute my ngOnInit methods again after the login is done?

ngOnInit() {
    this.loading = true;
    this._guestService.getAllGuests()
        .subscribe(
            guests => this.guests = guests,
            err => console.log(err),
            () => console.log('Request Complete')
         )
}  

login() {
    this.auth.login();
}
logout() {
    this.auth.logout();
}

auth.login service:

 login() {
   this.lock.show((error: string, profile: Object, id_token: string) => {
     if (error) {
       console.log(error);
     }
     localStorage.setItem('profile', JSON.stringify(profile));
     localStorage.setItem('id_token', id_token);
   });
 }
larz
  • 813
  • 1
  • 12
  • 29

2 Answers2

1

I would rename ngOnInit() something like getAllGuests() and then call getAllGuests() from within ngOnInit() and from within auth.login().

If you can't or do not want to insert this call in auth.login() I guess the thing could become a little more subtle and would require some sort of subscription mechanism using Observables, but before starting this path I would make sure you really need it.

I hope this helps

Picci
  • 16,775
  • 13
  • 70
  • 113
1

Here is an extension to Picci's answer, I would call getAllGuests on subscribe of login():

 ngOnInit(){
    this.getAllGuests();
    }

    getAllGuests() {
        this.loading = true;
        this._guestService.getAllGuests()
            .subscribe(
                guests => this.guests = guests,
                err => console.log(err),
                () => console.log('Request Complete')
             )
    }  

    login() {
        this.auth.login().subscribe(()=> this.getAllGuests());
    }
    logout() {
        this.auth.logout();
    }
Som
  • 460
  • 1
  • 5
  • 11
  • so my `this.auth.login()` service has to return a success from the login with an observable? – larz May 12 '16 at 21:16
  • it has to return Observable. check this post for more details: http://stackoverflow.com/questions/33675155/creating-and-returning-observable-from-angular-2-service – Som May 12 '16 at 21:18
  • can you give me an advice how can I fire the 'getAllGuestd' method AFTER the login was successful? – larz May 14 '16 at 15:04
  • Call 'getAllGuestId()' in the subscribe of login. This will make sure it's called after login is complete/successful. – Som May 14 '16 at 16:14