nailujpeloz
nailujpeloz

Reputation: 57

Http service response throw 401 until reload app Ionic2

I have an Ionic 2 app.

Login works perfect and redirects to other page but the info doesn't load, on the console I see 401 error.

Image after redirect:

Image after redirect

When I reload browser data is loaded

Image after reload:

Image after reload

loginForm(){
const data = {
  "username" : this.login.value.username,
  "email" : this.login.value.username,
  "password" : this.login.value.password,
}
this.dataService.loginUser(data).subscribe(
    (data) => {
      let token = data.key;
      this.dataService.checkAccessUserGroup(token).subscribe(
        (data) => {
          if(data[0] == 200){
            this.storage.set('access_token', token);
            //location.reload();
            this.appCtrl.getRootNav().setRoot(IndexPage);
          }
          if(data[0] == 500){
            this.generateAlert("Error",'No tienes permisos adecuados para acceder. Ponte en contacto con el administrador de tu Deck.');
          }
        },
        (err) => {
          if(err.status == 400){
            this.generateAlert("Error",'No hemos podido verificar tus datos. Intentalo de nuevo');
          }
        }
      );
    },
    (err) => {
      if(err.status == 400){
        this.generateAlert("Error",'Usuario o constraseña no válido. Intentalo de nuevo');
      }
    }
  );
}

How can I solve this problem?

Upvotes: 0

Views: 264

Answers (1)

Swapnil Patwa
Swapnil Patwa

Reputation: 4099

It is because storage is asynchronous, redirection should be inside the callback of set. However, sharing a better approach to deal with the token.

I use ionic storage to store the token and a provider config.ts which hold the token during run time.

config.ts

import { Injectable } from '@angular/core';  
@Injectable()
export class TokenProvider { 
    public token: any;
    public user: any = {}; 

  constructor(  ) { }
  setAuthData (data) { 
    this.token = data.token; 
    this.user = data
  }
  dropAuthData () {
    this.token = null;
    this.user = null;
  }
}

auth.ts

import { TokenProvider} from '../../providers/config';

constructor(public tokenProvider: TokenProvider) { }

login() {
      this.api.authUser(this.login).subscribe(data => {
        this.shared.Loader.hide(); 
          this.shared.LS.set('user', data); 
          this.tokenProvider.setAuthData(data); 
          this.navCtrl.setRoot(TabsPage); 
      }, err => {
        console.log(err);
        this.submitted = false;
        this.shared.Loader.hide();
        this.shared.Toast.show('Invalid Username or Password');
        this.login.password = null;
      });
}

and i do a check when app launch. app.component.ts (in constructor)

shared.LS.get('user').then((data: any) => {
      if (!data) {
        this.rootPage = AuthPage;
      } else {
        tokenProvider.setAuthData(data);
        this.rootPage = TabsPage;
      } 
    });

api.provider.ts

  updateUser(data): Observable < any > {
        let headers = new Headers({
            'Content-Type': 'application/json',
            'X-AUTH-TOKEN': (this.tokenProvider.token)
        });
    return this.http.post(`${baseUrl}/updateUser`, JSON.stringify(data), {
            headers: headers
        })
        .map((response: Response) => {
            return response.json();
        })
        .catch(this.handleError);
}

And last logout.ts

  logOut(): void {
    this.shared.Alert.confirm('Do you want to logout?').then((data) => {
      this.shared.LS.remove('user').then(() => {
        this.tokenProvider.dropAuthData();
        this.app.getRootNav().setRoot(AuthPage);
      }, () => {
        this.shared.Toast.show('Oops! something went wrong.');
      });
    }, err => {
      console.log(err);
    })

  }

Upvotes: 0

Related Questions