我正在使用 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>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句