angular - 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() {
}
}
我想在成功登录后显示用户名
解决方案
您可以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>
推荐阅读
- wordpress - 构建自定义 Elementor Widget-Wordpress
- javascript - @azure/storage-blob 中的 TokenCredential 中的令牌是什么,如何获取?
- azure - Azure 模板 - 根据所选资源组动态生成参数值
- regex - 如何使用正则表达式在索引时(使用 tstats)从不同的父键中提取具有相同子键的 json 字段?
- javascript - Node.js + express 如何在请求正文中添加字符串?
- google-app-engine - Google App Engine 中实体和存储桶之间的关系是什么
- java - 使用 Kotlin 的 Flyway 迁移失败
- batch-file - 批处理命令查找包含特定字符的文件
- scala - 使用 spark/scala 将文件从子目录复制到 hdfs 中的基目录
- swiftui - swiftui foreach 导航链接立即弹出