首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在角类型记录中获得本地存储的当前日志用户的用户名

如何在角类型记录中获得本地存储的当前日志用户的用户名
EN

Stack Overflow用户
提问于 2022-03-22 10:57:36
回答 1查看 802关注 0票数 0

我有一个棱角分明的应用程序,用户可以登录他的电子邮件和密码。因此,我需要当当前用户连接到菜单仪表板上显示他的名字时,就像欢迎詹姆斯一样,通过使用app.component.html显示( localStorage )。我从mysql数据库中获取所有信息。

代码:

login.component.html :

代码语言:javascript
复制
<h1 style="text-align:center">
  <img src="../../assets/images/logo.png">
</h1>
<div class="login-wrap">
  <div class="login-html">

    <div class='login'>
      <div class='col-md-4 offset-4 mt-5' *ngIf='!this.isLogin'>
        <h2 class="login-header">S'identifier</h2>
        <form class="login-container" #myform="ngForm" (ngSubmit)="onSubmit(myform)">
          <div class='form-group'>
            <input class='form-control' type="email" name="email" placeholder="email" ngModel>
          </div>

          <div class='form-group'>
            <input class='form-control' type="password" name="password" placeholder="Password"
              [type]="hide ? 'password': 'text'" [(ngModel)]="passwordValue">
            <span class="material-icons" matSuffix (click)="hide = !hide">
              {{hide ? 'visibility': 'visibility_off'}}
            </span>
          </div>
          <input class='btn btn-outline-info' type="submit" value="Login">
        </form>
      </div>
      <div class='col-md-4 offset-4 mt-5' *ngIf='this.isLogin'>

        <h1>You are logged in</h1>
        <button class='btn btn-outline-info' (click)='logout()'>Log-out</button>

      </div>
    </div>
  </div>
</div>

login.component.ts :

代码语言:javascript
复制
export class LoginComponent implements OnInit {
  isLogin: boolean = false
  errorMessage: any
  hide =true;
  passwordValue='';

  constructor(
    private _api: ApiService, 
    private _auth: AuthService, 
    private _router:Router,  private toastr : ToastrService) { }

  ngOnInit(){
    this.isUserLogin(); 
  }
  
  onSubmit(form: NgForm) {
    
    console.log('Your form data : ', form.value);
    this._api.postTypeRequest('user/login', form.value).subscribe((res: any) => {
     
      switch (res.status) {
        case 0:
            this.toastr.error("you have a problem","Erreur");
            break;
        case 1:
            this._auth.setDataInLocalStorage('userData', JSON.stringify(res.data));  
            this._auth.setDataInLocalStorage('token', res.token);  
            this._router.navigate(['']);
            break;
        case 2:
            this.toastr.warning("your email or password is incorrect","Warning");
            this.passwordValue = '';
            break;
    }
    })
  }

  isUserLogin(){
    if(this._auth.getUserDetails() != null){
        this.isLogin = true;
    }
  }

  logout(){
    this._auth.clearStorage()
    this._router.navigate(['']);
  }
}

app.component.html (菜单) :

代码语言:javascript
复制
<nav class="menu">
    <ol>
        <li class="menu-item"><a routerLink="adherents">Adherents</a></li>
        <li class="menu-item">
            <a routerLink="factures">Factures</a>
        </li>
        <li class="menu-item">
            <a routerLink="logs">Logs</a>
        </li>
        <li class="menu-item">
            <a routerLink="regions">Regions</a>
        </li>
        <li class="menu-item">
            <a routerLink="roles">Roles</a>
        </li>
        <li class="menu-item">
            <img class="img" src="../assets/images/user.png">
            <a>welcome james</a>
            <ol class="sub-menu">
                <li class="menu-item"><a routerLink="/login">LogOut</a></li>
            </ol>
        </li>
    </ol>
</nav>
<router-outlet></router-outlet>

auth-卫士服务:

代码语言:javascript
复制
@Injectable({
  providedIn: 'root'
})
export class AuthGuardService {

  constructor( private _authService: AuthService,
    private _router: Router) { }

    canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
      if (this._authService.getToken()) {
        return true;
      }
     
      this._router.navigate(['/login']);
      return false;
    }
    
}

auth.service.ts:

代码语言:javascript
复制
@Injectable({
  providedIn: 'root'
})
export class AuthService {

  constructor() { }


  getUserDetails() {
    if(localStorage.getItem('userData')){
      return localStorage.getItem('userData')
    }else{
      return null
    }
    
  }
  setDataInLocalStorage(variableName, data) {
      localStorage.setItem(variableName, data);
  }
  getToken() {
      return localStorage.getItem('token');
  }
  clearStorage() {
      localStorage.clear();
  }
  
  
}
EN

回答 1

Stack Overflow用户

发布于 2022-03-22 11:10:20

在您的app.component.ts上,您可以创建一个变量,在其中获取userData,并使变量.userName

代码语言:javascript
复制
import { Component } from '@angular/core';

@Component({
     selector: 'app-root',
     templateUrl: './app.component.html',
     styleUrls: ['./app.component.scss']
})
export class AppComponent {
    title = 'cgem';
    user:any;
    constructor(){}
    ngOnInit() {
    //I forgot that you have to try to recover the user in the ngOnit. 
        try{
           this.user= JSON.parse(localStorage.getItem("userData"));
        }catch(error){}    
    }

   //after 
    
 }  

在你的app.component.html上你可以打电话给用户

代码语言:javascript
复制
...
<img class="img" src="../assets/images/user.png">
<a>welcome {{user.name}}</a>
<ol class="sub-menu">
...
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71570891

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档