我开发 Angular 应用程序并使用 oauth 进行身份验证。我安装了 oidc-client npm 包。并且各方面工作正常。但是 ngoninit 方法有一点错误。这是我的代码:
ngOnInit() {
this.subscription = this.authService.authNavStatus$.subscribe(status => {
this.isAuthenticated = status;
console.log('header'+status);
});
}
我在控制台中看到的是:
正如您在图像上看到的,oninit 方法调用了两次。第一次返回 false 的状态,但第二次返回 true。
有关更多详细信息,我的 AuthService 在这里:
export class AuthService extends BaseService {
// Observable navItem source
private _authNavStatusSource = new BehaviorSubject<boolean>(false);
// Observable navItem stream
authNavStatus$ = this._authNavStatusSource.asObservable();
private _loginChangedSubject = new Subject<boolean>();
public loginChanged = this._loginChangedSubject.asObservable();
private manager = new UserManager(getClientSettings());
private user: User | null;
constructor(private http: HttpClient, private configService: ConfigService) {
super();
this.manager.getUser().then(user => {
console.log(user);
this.user = user;
this._authNavStatusSource.next(this.isAuthenticated());
});
// this.manager.events.addAccessTokenExpired(_ => {
// console.log(this.user);
// this._loginChangedSubject.next(false);
// })
}
login() {
return this.manager.signinRedirect();
}
async completeAuthentication() {
this.user = await this.manager.signinRedirectCallback();
this._authNavStatusSource.next(this.isAuthenticated());
}
async finishLogout() {
this.user = null;
this._loginChangedSubject.next(false);
return this.manager.signoutRedirectCallback();
}
register(userRegistration: any) {
return this.http.post(this.configService.authApiURI + '/account', userRegistration).pipe(catchError(this.handleError));
}
isAuthenticated(): boolean {
return this.user != null && !this.user.expired;
}
get authorizationHeaderValue(): string {
return `${this.user!.token_type} ${this.user!.access_token}`;
}
get name(): string {
return this.user != null ? this.user.profile.name! : '';
}
async signout() {
await this.manager.signoutRedirect();
}
}
更新:
谢谢@MikeOne 和@Icekson,现在问题是为什么状态一开始是假的,第二次尝试是真的?
更新 2: 这是我的 header.component.html:
<pec-header [isAuth]="isAuthenticated"></pec-header>
<br>
<br>
<hr>
<h2>{{isAuthenticated}}</h2>
<hr>
和 header.component.ts 在这里:
export class MyHeaderComponent implements OnInit {
private destroy$: Subject<void> = new Subject<void>();
userPictureOnly: boolean = false;
user: any;
isAuth: boolean;
name: string;
subscription: Subscription;
isAuthenticated: boolean;
constructor(private router: Router, private helpers: Helpers, private authService: AuthService) {
}
ngOnInit() {
this.subscription = this.authService.authNavStatus$.subscribe(status => {
this.isAuthenticated = status;
console.log('header component => ' + status);
});
this.name = this.authService.name;
}
}
h2 标记显示“真”值,但 pec-header 标记的绑定值表现得好像它是假的。
谢谢