在Angular中从window身份验证中获取用户名,可以通过以下步骤实现:
@angular/common
模块。Injectable
和DOCUMENT
符号:import { Injectable, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/common';
AuthService
的服务,并使用@Injectable
装饰器进行注解:@Injectable({
providedIn: 'root'
})
export class AuthService {
constructor(@Inject(DOCUMENT) private document: Document) { }
getUsername(): string {
return this.document.defaultView?.name || '';
}
}
getUsername
方法中,通过this.document.defaultView?.name
获取到当前窗口的用户名。这里使用了可选链操作符?.
来确保在没有用户名时不会抛出错误。AuthService
服务,并调用getUsername
方法:import { Component } from '@angular/core';
import { AuthService } from './auth.service';
@Component({
selector: 'app-my-component',
template: `
<div>
Username: {{ username }}
</div>
`
})
export class MyComponent {
username: string;
constructor(private authService: AuthService) {
this.username = this.authService.getUsername();
}
}
通过以上步骤,你就可以在Angular中从window身份验证中获取到用户名了。请注意,这里的实现是基于浏览器环境下的window对象,因此适用于前端开发中的身份验证场景。
领取专属 10元无门槛券
手把手带您无忧上云