简体   繁体   中英

Angular service wait for Observable in constructor

I have an Angular 2 service with this constructor:

constructor(public fireAuth: AngularFireAuth)
{
    console.log('1');
    fireAuth.authState.subscribe(user =>
    {
        console.log('2');
        this.user = user;
    });
    console.log('3');
}

When it's instantiated, the log order is 1, 3 and 2, because the 2nd log is inside the Observable. I can't use it async/await because it's in the service constructor . Is there any way to make this call synchronous?

You need to use the complete callback;

console.log('1');
fireAuth.authState.subscribe(
  user => {
      console.log('2');
      this.user = user;
  },
  error => console.error(error),
  () => {
      console.log('3');
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM