import { Component, OnInit } from '@angular/core';
import { AuthDataService } from '../Service/authDataService';
import { map } from 'rxjs';
import { User } from '../Model/userModel';
import { CommonModule } from '@angular/common';
@Component({
selector: 'app-success',
standalone: true,
imports: [CommonModule],
templateUrl: './success.component.html',
styleUrl: './success.component.css',
})
export class SuccessComponent implements OnInit {
authenticated = false;
constructor(private authService: AuthDataService) {}
ngOnInit(): void {
this.authService.userSubject.subscribe((user) => {
console.log(user);
this.authenticated = !!user;
console.log('In the body of subscribe');
//true here
console.log(this.authenticated);
});
//still false
console.log('outside');
console.log(this.authenticated);
}
check() {
//false here to
console.log(this.authenticated);
}
}
我正在尝试使用订阅将用户对象的更改发送到我的所有组件...但即使在发出更改后,它似乎也没有更改布尔值...
订阅内部的代码称为异步代码,与同步代码不同,异步代码发生在稍后的时间点,它等待事件发生,但其下面的代码不会等待订阅完成,所以要处理这个问题,您需要移动您希望在订阅内进行身份验证后发生的逻辑
ngOnInit(): void {
this.authService.userSubject.subscribe((user) => {
console.log(user);
this.authenticated = !!user;
console.log('In the body of subscribe');
//asynchronous move all your logic inside here!
console.log(this.authenticated);
});
// synchronous does not wait for subscribe to complete
console.log('outside');
console.log(this.authenticated);
}