服务构造函数两次调用

时间:2018-12-08 01:33:11

标签: angular

我提供以下服务:

@Injectable({
  providedIn: 'root'
})

export class AuthService {

  user: Observable<User>;
  checkEmailInterval: any;

  constructor(
    private afAuth: AngularFireAuth,
    private afStore: AngularFirestore,
    private router: Router
  ) {
    this.user = this.afAuth.authState.pipe(
      switchMap(user => {
        if (user) {
          console.log(user);
          if (!user.emailVerified) {
            console.log(this.checkEmailInterval);
            clearInterval(this.checkEmailInterval);
            this.checkEmailInterval = setInterval(this.checkEmailVerified.bind(this), 5000);
          }
          return this.afStore.doc<User>(`users/${user.uid}`).valueChanges();
        }
        else {
          console.log("NO USER");
          return of(null);
        }
      })
    );
  }

每当我打开应用程序时,其构造函数都会被调用两次。这是预期的行为吗?我以为可能是为注入的每个组件调用构造函数,但是我在3个组件中使用了该服务。

除此以外,我真的不确定要共享代码的哪一部分。有什么想法吗?

1 个答案:

答案 0 :(得分:-1)

您可以尝试在ngOnInit中移动此逻辑。按照角度,所有将ProvidedIn属性用作“ root”的可注入服务将被视为单例类,并且将被实例化一次。

@Injectable({
  providedIn: 'root'
})

export class AuthService implements OnInit {

  user: Observable<User>;
  checkEmailInterval: any;

  constructor(
    private afAuth: AngularFireAuth,
    private afStore: AngularFirestore,
    private router: Router
  ) {}

  ngOnInit(){
    this.user = this.afAuth.authState.pipe(
      switchMap(user => {
        if (user) {
          console.log(user);
          if (!user.emailVerified) {
            console.log(this.checkEmailInterval);
            clearInterval(this.checkEmailInterval);
            this.checkEmailInterval = setInterval(this.checkEmailVerified.bind(this), 5000);
          }
          return this.afStore.doc<User>(`users/${user.uid}`).valueChanges();
        }
        else {
          console.log("NO USER");
          return of(null);
        }
      })
    );
  }
}