用户会话IONIC 2

Car*_*ery 2 session ionic2 angular

我正在尝试记录用户,并在另一个页面中获取该用户的数据,但我到处都有"未定义"...

我的服务:

 export class User {
   password: string;
   email: string;
   id:any;

  constructor(data) {
    this.id = data;
    return this.id;
  }

  getUser(){
  return this.id;
  }
}

@Injectable()

export class AuthService {
Run Code Online (Sandbox Code Playgroud)

login(value){

let headers = new Headers({
'Content-Type':'application/json'
});
let options = new RequestOptions({
  headers: headers
});
let body = value;

return new Promise(resolve=> {

  this.http
    .post(this.url+'/user/auth', body)
    .map(res => res.json())
    .subscribe(
        data => {
          this.user = new User(data);

          resolve(this.user);

          console.log(this.user);


            this.local = new Storage();
            this.local.set('User', this.user);
            this.local.get('User').then((val) => {
              console.log('You are', val)
            });

        });
});
Run Code Online (Sandbox Code Playgroud)

}

我的代码中的其他地方:

 public getUserInfo():User{
  console.log(this.user)
  return this.user;
 }
Run Code Online (Sandbox Code Playgroud)

在home.ts:

 public test;  
 this.test = this.auth.getUserInfo();
Run Code Online (Sandbox Code Playgroud)

谢谢您的帮助 !我也试过使用存储,但有时,页面之间不共享数据,那么如何使用我的用户信息呢?

AJT*_*T82 7

你的问题对于代码的位置和执行的顺序有点模糊,我只是提供一个如何使用的答案localStorage,因为你用你自己的话说你登录,你导航到其他页面然后检索用户.我注意到的第一件事是,您订阅了您的服务,我建议您在组件(您登录的组件)中进行订阅.

在您的服务中,您希望在用户通过身份验证时实际检查响应,但在此我不会考虑这一点.

AuthService:

login(value) {
  // other code here
  this.http.post(this.url+'/user/auth', body)
    .map((res:Response) => {
      let resp = res.json();
      // set user in local storage
      localStorage.setItem('user', JSON.stringify(resp));
      return resp;
    });
}
Run Code Online (Sandbox Code Playgroud)

然后,您可能希望在authService中有一个方法将此用户返回给请求它的组件:

getUser() {
  return JSON.parse(localStorage.getItem('user'))
}
Run Code Online (Sandbox Code Playgroud)

所以回到你的登录页面,在那里你调用你的登录方法,所以它可能是这样的......

login(credentials) {
  this.authService.login(credentials)
    .subscribe(data => {
       // here user have already been saved to local storage and we can navigate
       this.router.navigate(['yourComponent']);
    });
}
Run Code Online (Sandbox Code Playgroud)

然后在您的组件中,导航后,您只需在您的用户中请求此用户OnInit并将其存储到组件中的本地变量:

ngOnInit() {
  this.user = this.authService.getUser();
}
Run Code Online (Sandbox Code Playgroud)

有了这个,一切都被正确链接:

  1. 登录
  2. Http请求
  3. 通过响应将用户存储在本地存储中
  4. 导航到其他组件
  5. 在组件中从本地存储中检索用户

当然,您不需要使用本地存储,只需检查您的操作是否正确链接.

希望这可以帮助!:)