首页 > 解决方案 > Angular 7 - 成功登录后显示用户名

问题描述

我正在使用 Angular 7 和 Laravel 创建用户登录。Laravel 为 Angular 提供端点。我成功创建了用户登录,但我不知道如何显示登录的用户名

我已经做到了,成功登录后,它会重定向到仪表板页面。我为登录创建了一个服务(jarwis.service)。

jarwis(login) service

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class JarwisService {

  private baseUrl = 'http://localhost/cloudengine-sandbox/cloudengine/public/api';
  //private baseUrl = '/api';


  constructor(private http:HttpClient) { }

  signup(data){
    return this.http.post(`${this.baseUrl}/signup`, data)
  }
  login(data){
    return this.http.post(`${this.baseUrl}/login`, data)
  }

  sendPasswordResetLink(data) {
    return this.http.post(`${this.baseUrl}/sendPasswordResetLink`,data)
  }
}

登录组件

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Subscriber } from 'rxjs';
import { JarwisService } from '../../services/jarwis.service';
import { TokenService } from '../../services/token.service';
import { Router } from '@angular/router';
import { AuthService } from '../../services/auth.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {

  public form = {
    email:null,
    password:null
  };

 public error = null;
  constructor(
    private Jarwis:JarwisService,
    private Token:TokenService,
    private router:Router,
    private Auth:AuthService
  ) { }

  onSubmit() {
  this.Jarwis.login(this.form).subscribe(
     data => this.handleResponse(data),
     error => this.handleError(error)
  );
  }

  handleResponse(data){
 this.Token.handle(data.access_token);
 this.Auth.changeAuthStatus(true);
 this.router.navigateByUrl('/home');
  }


  handleError(error){
 this.error = error.error.error;
  }

  ngOnInit() {
  }

}

我想在成功登录后显示用户名

标签: angularlaravel

解决方案


您可以sessionStorage在成功登录后将用户名设置为并在这样的另一个组件中使用

handleResponse(data){
  this.Token.handle(data.access_token);
  this.Auth.changeAuthStatus(true);
  sessionStorage.setItem('loggedUser', data.Username);
  this.router.navigateByUrl('/home');
}

在 Home 组件 ts 文件中

export class NavbarComponent implements OnInit {
    userDisplayName = '';
    ngOnInit() {
       this.userDisplayName = sessionStorage.getItem('loggedUser');
    }
}

在 HTML 文件中

<div class="username">Username: {{userDisplayName}}</div>

推荐阅读