Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 安全地存储当前用户_Angular_Authentication_Storage - Fatal编程技术网

Angular 安全地存储当前用户

Angular 安全地存储当前用户,angular,authentication,storage,Angular,Authentication,Storage,我正在使用angular 8,我想存储我的当前用户!我认为每次我想要获取当前用户时调用api是不现实的,而且将其保存在本地存储中是不安全的! 有什么帮助吗?将其缓存在服务中,例如 @Injectable() export class UserService { user: User; getCurrentUser = (): Observable<User> => this.user ? of(this.user) :

我正在使用angular 8,我想存储我的当前用户!我认为每次我想要获取当前用户时调用api是不现实的,而且将其保存在本地存储中是不安全的!
有什么帮助吗?

将其缓存在服务中,例如

@Injectable()
export class UserService {
    user: User;
    getCurrentUser = (): Observable<User> =>
     this.user ?
        of(this.user) :
        this.http.get<User>(`${this.endpoint}/loggedinuser`)
            .pipe(tap(u => {
                this.user = u;
            }))
@Injectable()
导出类用户服务{
用户:用户;
getCurrentUser=():可观察=>
这个用户?
属于(此用户):
this.http.get(`${this.endpoint}/loggedinuser`)
.管道(水龙头(u=>{
这个用户=u;
}))

编辑:@AJT82在注释中使用share()运算符的解决方案可能更干净更好。但是将其存储在变量中有它的优点,更容易注销(只需执行此操作。user=null)将用户作为用户属性而不是可观察属性进行访问可能会很方便。

这是存储currentUser的选项之一,我希望这会有所帮助

基本上,您需要将当前用户存储在localStorage或sessionStorage中

例如:

this.http.get<any>('${this.endpointURL}/currentUser}).subscribe(res=>{

  // If you want to store token
  localStorage.setItem('current_user', res.authentication_token ) 

  // If you want to store complete user object
  localStorage.setItem('current_user', JSON.stringify(res.user) )
})
this.http.get('${this.endpointURL}/currentUser}).subscribe(res=>{
//如果你想储存代币
localStorage.setItem('current_user',res.authentication_token)
//如果要存储完整的用户对象
localStorage.setItem('current_user',JSON.stringify(res.user))
})

就这样。愉快的编码。

看看
共享
:但请记住,当用户注销时,要正确处理此问题。