有不同的选项可以得到相同的结果。
我将与您分享其中之一。
首先,您必须创建一个全局服务
AuthService.service.ts
@Injectable({
providedIn: 'root'
})
export class AuthServiceService {
private _sesionState: BehaviorSubject<boolean>;
constructor() {
this._sesionState = new BehaviorSubject(false)
}
public changeLoggedIn(isLoggedIn: boolean): void{
this._sesionState.next(isLoggedIn);
}
public onLoggedInChanged(){
return this._sesionState.asObservable();
}
}
然后,例如在您的登录页面中。
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
constructor(private authService: AuthServiceService) {}
public login(): void {
// Your logic here
// If gets a success login
this.authService.changeLoggedIn(true);
}
终于在你的导航栏组件中
@Component({
selector: 'app-navbar',
templateUrl: './navbar.component.html',
styleUrls: ['./navbar.component.css']
})
export class NavbarComponent implements OnInit {
constructor(private authService: AuthServiceService) {}
public getLoggedInUser(): void {
this.authService.onLoggedInChanged().subscribe((loggedIn: boolean) => {
// If(loggedIn) =>
})
}
在这种情况下,我们使用主题来共享应用程序周围的信息。它可以是任何你想要的,任何类型的数据类型。
因此,如果您想了解更多潜在的主题
我会推荐你Subjects, BehaviorSubjects, ReplySubjects