我想在成功登录后显示我的用户名。由于我正在使用登录令牌,并且我的登录逻辑是单独编写的,而不是在我的auth文件中,所以我将包括所有需要的文件,以更好地理解
以下是登录组件文件
export class MyErrorStateMatcher implements ErrorStateMatcher {
isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
const isSubmitted = form && form.submitted;
return !!(control && control.invalid && (control.dirty || control.touched || isSubmitted));
}
}
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
mode: ProgressBarMode = 'indeterminate';
value = 50;
bufferValue = 75;
loading:boolean=false;
matcher = new MyErrorStateMatcher();
loginForm = new FormGroup({
email: new FormControl('', [Validators.email, Validators.required ]),
password: new FormControl('', [Validators.required, Validators.min(3) ])
})
get email() { return this.loginForm.get('email'); }
get password() { return this.loginForm.get('password'); }
errorMail = '';
getErrorMessage(emailInput:HTMLInputElement) {
const mail=/^w+([.-]?w+)*@meltwater.com/;
if(!emailInput.value.match(mail)){
this.errorMail='Email or password are not valid'
}
else{
this.loading=true;
}
}
constructor(
private loginService: LoginService,
private saveUserData:AuthService,
private router: Router,
private cookie:CookieService) { }
userDisplayName = ''
ngOnInit(): void {
}
rememberMe(e){
if(e.target.checked){
this.cookie.set('value',this.loginForm.value);
}
}
onSubmit(event) {
event.preventDefault()
console.log('value',this.loginForm.value)
if(this.errorMail.length === 0) {
this.loginService.login(this.loginForm.value).subscribe((res:any) => {
console.log('login response', res)
if(res.auth.success === true) {
localStorage.setItem('auth', JSON.stringify(res.auth))
this.loginService.loggedIn$.next(res.auth)
this.saveUserData.saveAuthData(res)
sessionStorage.setItem('loggedUser', res.Username);
this.router.navigateByUrl('/search/list')
} else {
this.errorMail='Email or password is not valid'
}
})
}
}
// returnUserName(){
// return this.userDisplayName = sessionStorage.getItem('loggedUser');
// }
}
以下是登录服务文件
export class LoginService {
constructor(private http: HttpClient) { }
loggedIn$ = new BehaviorSubject(null)
login(creds) {
console.log('creds',creds)
return this.http.post<LoginResponse>('https://backend.url/login', {creds})
}
}
这是我的身份验证服务文件,我想可能不需要它
import { Injectable } from "@angular/core";
import { HttpClient } from "@angular/common/http";
import { Router } from "@angular/router";
import { Subject } from "rxjs";
import { BehaviorSubject } from 'rxjs';
@Injectable({ providedIn: "root" })
export class AuthService {
private isAuthenticated = false;
private token: string;
private email: string;
private authStatusListener = new Subject<boolean>();
constructor(private http: HttpClient, private router: Router) {}
getToken() {
return this.token;
}
getIsAuth() {
return this.isAuthenticated;
}
getAuthStatusListener() {
return this.authStatusListener.asObservable();
}
public saveAuthData(token: string) {
localStorage.setItem("token", token);
}
private clearAuthData() {
localStorage.removeItem("token");
}
logout() {
// this.token = null;
this.clearAuthData();
this.router.navigate(["/"]);
}
autoAuthUser() {
const authInformation = this.getAuthData();
this.token = authInformation.token;
this.isAuthenticated = true;
this.authStatusListener.next(true);
}
private getAuthData() {
const token = localStorage.getItem("token");
if (!token ) {
return;
}
return {
token: token
}
}
userDetails(){
sessionStorage.setItem('loggedUser', .email);
}
}
这是我想要显示我的用户名的地方:标题
以下是标题组件
import { AuthService } from './../../auth/auth.service';
import { LoginComponent } from './../../login/login.component';
import { Router } from '@angular/router';
import { Component, OnInit } from '@angular/core';
import { Subscription } from 'rxjs';
@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {
public userIsAuthenticated;
public userName = '';
constructor(public authService: AuthService,public router:Router, public user:LoginComponent) { }
onLogout(){
this.authService.logout();
this.router.navigateByUrl('/');
}
ngOnInit(): void {
this.userName = this.user.returnUserName() ;
}
}
这给我带来了一个错误,可能是bcz登录组件被导入了,我不太确定为什么会出现错误
您不能将组件作为服务注入,而是使用@ViewChild(LoginComponent)
,但这不会解决问题。
要获得username,请尝试在AuthService
中移动该方法。
希望能有所帮助。