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); }); } 
1
  • The code in ngOnInit() doesn't seem to depend on the current login status. Why do you want ngOnInit() to be executed again? Commented May 11, 2016 at 4:56

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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(); } 

4 Comments

so my this.auth.login() service has to return a success from the login with an observable?
it has to return Observable. check this post for more details: stackoverflow.com/questions/33675155/…
can you give me an advice how can I fire the 'getAllGuestd' method AFTER the login was successful?
Call 'getAllGuestId()' in the subscribe of login. This will make sure it's called after login is complete/successful.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.