如何获取当前的用户ID角4? [英] How to get current user id angular 4?

查看:93
本文介绍了如何获取当前的用户ID角4?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须获取当前用户ID才能在应用程序的不同部分使用它.

I have to get current user ID to use it in different parts in my app..

login.component.ts:

login.component.ts:

onSignin(form: NgForm){
const UserName = form.value.UserName;
const Password = form.value.Password;
this.authService.signinUser(UserName,Password).map(res => res.json())
 .subscribe(
   data => {
     if (data.Id == 0){
     this.invalid=true;
    }
    else{
      localStorage.setItem('isLoggedin', 'true');
      this.router.navigate(['/calendar']);
      console.log('Ok');
   }})}

auth.service.ts:

auth.service.ts:

signinUser(UserName,Password): Observable<any>{
  return this.http.get('http://api.##.com/api/security/signin?username='+UserName+'&password='+Password);
}

推荐答案

您可以从后端传递包含ID的令牌,也可以使用redux store将Redid存储在前端供您的应用程序使用.以下是Ang2 ng2 Redux软件包的链接. https://www.npmjs.com/package/ng2-redux 还有一个选项可以将其保存到本地存储中,但我不喜欢它. 您可以像这样使用会话存储将数据保存在前端

You can pass the token from the backend which will contain the id or you can use redux store which will store the id on the front end for your application to use. Below is the link for ng2 Redux package in angular. https://www.npmjs.com/package/ng2-redux There is also an option to save it into local storage but I will not prefer it.Or You can use session storage to save the data on the front end like this

使用该代码在会话中保存登录组件文件

saving in the session in your login Component file use this code

sessionStorage.setItem('id', data.id);
retrieving from the session//
var data = sessionStorage.getItem('id');
console.log(data) to see the id in the console

这篇关于如何获取当前的用户ID角4?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆