在angular8应用程序中成功登录后的打印用户名

问题描述 投票:0回答:1

我想在成功登录后显示我的用户名。由于我正在使用登录令牌,并且登录逻辑是单独编写的,而不是在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登录组件已导入,我不确定为什么会发生错误

node.js angular typescript angular8 mean-stack
1个回答
0
投票

您不能将组件作为服务注入,而是使用@ViewChild(LoginComponent),但这不能解决问题。

要获取用户名,请尝试在AuthService中移动该方法。

希望有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.