如果在Angular中成功验证后,顶部栏未渲染,可能是由于以下原因之一:
// topbar.component.ts
import { Component, OnInit } from '@angular/core';
import { AuthService } from 'path/to/auth.service';
@Component({
selector: 'app-topbar',
templateUrl: './topbar.component.html',
styleUrls: ['./topbar.component.css']
})
export class TopbarComponent implements OnInit {
showTopbar: boolean = false;
constructor(private authService: AuthService) { }
ngOnInit() {
this.authService.isAuthenticated().subscribe((isAuthenticated) => {
this.showTopbar = isAuthenticated;
});
}
}
// auth.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { BehaviorSubject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class AuthService {
private isAuthenticatedSubject = new BehaviorSubject(false);
constructor(private http: HttpClient) { }
isAuthenticated() {
return this.isAuthenticatedSubject.asObservable();
}
login(credentials) {
// Send login request to server
this.http.post('/api/login', credentials).subscribe((response) => {
// Update isAuthenticatedSubject based on server response
this.isAuthenticatedSubject.next(true);
});
}
logout() {
// Send logout request to server
this.http.post('/api/logout', {}).subscribe((response) => {
// Update isAuthenticatedSubject based on server response
this.isAuthenticatedSubject.next(false);
});
}
}
在你的登录组件中,调用验证服务的login
方法来执行登录逻辑,并在成功登录后重定向到你的顶部栏组件。
// login.component.ts
import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { AuthService } from 'path/to/auth.service';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent {
constructor(private router: Router, private authService: AuthService) { }
login() {
// Perform login logic and redirect to topbar component
this.authService.login({ username: 'your_username', password: 'your_password' });
this.router.navigate(['/topbar']);
}
}
确保在你的应用中正确配置路由,以便将登录组件和顶部栏组件连接起来。