Caroline Teulery
Caroline Teulery

Reputation: 45

User session IONIC 2

I'm trying to log an user, and get the data of this user in another page, but I have "undefined" everywhere...

My service :

 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 {

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)
            });

        });
});

}

Somewhere else in my code :

 public getUserInfo():User{
  console.log(this.user)
  return this.user;
 }

In home.ts :

 public test;  
 this.test = this.auth.getUserInfo();

Thank you for your help ! I've also tried to used Storage, but sometimes, the data is not shared between pages, so How can I use my User info ?

Upvotes: 2

Views: 6288

Answers (1)

AVJT82
AVJT82

Reputation: 73357

Your question being a bit vague as to where code is and in what order it's performed, I'll just provide an answer on how you could do this, using localStorage, since you in your own words said you log in, you navigate to other page and then retrieve the user. First thing I noticed, is that you subscribe in your service, I suggest you do it in the component (your component where you login).

In your service you want to actually check the response if the user is authenticated, here I won't regard that though.

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;
    });
}

Then you might want to have a method in the authService to return this user to the components requesting it:

getUser() {
  return JSON.parse(localStorage.getItem('user'))
}

So back to your login page, where you call your login method, so it could be something like this...

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']);
    });
}

And then in your component, after navigation, you just request this user in your OnInit and store it to a local variable in the component:

ngOnInit() {
  this.user = this.authService.getUser();
}

With this, everything is chained properly:

  1. Login
  2. Http request
  3. Store user in local storage from response
  4. Navigate to other component
  5. In the component retrieve user from local storage

Of course you do not need to use local storage, just check that your actions are chained properly.

Hope this helps! :)

Upvotes: 7

Related Questions