我正在使用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() {
}
}
我要在成功登录后显示用户名
答案 0 :(得分:1)
您可以在成功登录后将用户名设置为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>