我正在使用AngularFire和Angular 8来构建应用程序,但是我遇到了一个愚蠢的问题(我相信它实际上是愚蠢的)。
我构建了一个简单的服务来包装AngularFireAuth
:
import { Injectable } from '@angular/core';
import { AngularFireAuth } from '@angular/fire/auth';
import { User } from 'firebase';
import { Subject } from 'rxjs';
import { MessageService } from 'primeng/api';
@Injectable({
providedIn: 'root'
})
export class AuthService {
private user: Subject<User> = new Subject();
private isLoggedIn: Subject<boolean> = new Subject();
constructor(private afAuth: AngularFireAuth, private messageService: MessageService) {
this.afAuth.auth.onAuthStateChanged(user => {
this.user.next(user);
this.isLoggedIn.next(user !== null);
});
}
isAuthenticated() {
return this.isLoggedIn.asObservable();
}
}
然后,将其注入我的HomeComponent
中,并订阅Observable
方法返回的isAuthenticated
:
import { Component, OnInit } from "@angular/core"
import { AuthService } from '../auth/auth.service';
@Component({
selector: 'app-homepage',
styleUrls: ['./homepage.component.scss'],
templateUrl: './homepage.component.html'
})
export class HomepageComponent implements OnInit {
isAuthenticated: boolean = false;
constructor(private authService: AuthService) { }
ngOnInit() {
this.authService.isAuthenticated().subscribe((isAuth) => {
this.isAuthenticated = isAuth;
console.log(`User is authenticated? ${this.isAuthenticated}`);
});
}
}
但是,当调用传递给subscribe
方法的箭头函数时,不会执行任何重新渲染。但是,console.log
调用确实在DevTools上显示“用户已通过身份验证?是”。
我已经完成的其他一些测试:如果我从传递给setTimeout
的arrow函数中调用subscribe
,则结果是相同的。没有重新渲染,DevTools上的消息显示“用户已通过身份验证?是”。
但是,如果我在setTimeout
之外调用subscribe
(在此测试中有10秒的延迟),则在这10秒钟后将重新渲染该组件:
import { Component, OnInit } from "@angular/core"
import { AuthService } from '../auth/auth.service';
@Component({
selector: 'app-homepage',
styleUrls: ['./homepage.component.scss'],
templateUrl: './homepage.component.html'
})
export class HomepageComponent implements OnInit {
isAuthenticated: boolean = false;
constructor(private authService: AuthService) { }
ngOnInit() {
this.authService.isAuthenticated().subscribe((isAuth) => {
this.isAuthenticated = isAuth;
console.log(`User is authenticated? ${this.isAuthenticated}`);
});
setTimeout(() => {
this.isAuthenticated = true;
console.log(`User is authenticated? ${this.isAuthenticated}`);
}, 10000)
}
}
我在这里想念什么?我误会了什么?
答案 0 :(得分:0)
这是因为在组件初始化之后,您正在调用身份验证 在构造函数中调用它有效
import { Component, OnInit } from "@angular/core"
import { AuthService } from '../auth/auth.service';
@Component({
selector: 'app-homepage',
styleUrls: ['./homepage.component.scss'],
templateUrl: './homepage.component.html'
})
export class HomepageComponent implements OnInit {
isAuthenticated: boolean = false;
constructor(private authService: AuthService) {
this.authService.isAuthenticated().subscribe((isAuth) => {
this.isAuthenticated = isAuth;
console.log(`User is authenticated? ${this.isAuthenticated}`);
});
}
ngOnInit(){}
}