0


I am trying to create a Ionic v3 app able to consume REST APIs using an api token as logging method. After the user performs the login, the variable currentUser gets set and from now then the AuthInterceptor will always send the api token attached to all requests.

However, apparently the currentUser is always null even though the alert in the login, used as a check, always shows the correct user first name.

AuthInterceptor.ts

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
    currentUser: any;

    constructor(public storage: Storage) {
        this.storage.get('currentUser').then((val) => {
            this.currentUser = JSON.parse(val);  
        });
    }

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        // add authorization header with api token if available

        console.log(this.currentUser);

        if (this.currentUser && this.currentUser.api_token) {
                request = request.clone({
                    setHeaders: {
                        'Authorization': `Bearer ${this.currentUser.api_token}`
                    }
                });
        }
        return next.handle(request);
    }
}

AuthSvc.ts

 login(email: string, password: string) {
        return this.http.post<any>('login', { email: email, password: password })
            .map(data => {
                // login successful if there's an api token in the response
                if (data.user && data.user.api_token) {

                    this.setUser(data.user);

                    return data.user;
                } 
            });
    }

setUser(user) {
        console.log('setUser');
        // store user details and the token in local storage to keep user logged in between page refreshes
        this.storage.set("currentUser", JSON.stringify(user));
    }

login.ts (page)

this.authSvc.login(this.user.email, this.user.password)
    .subscribe(
       data => {
           alert('Hi '+data.name);
           this.navCtrl.setRoot(HomePage);
       },
       error => {
    });

The API returns a JSON object consisting of

{
 "success": true,
 "user": User obj
}
Anelito
  • 213
  • 3
  • 16
  • Well where do you actually set the user to the storage? Cant see anywhere... – AT82 Mar 16 '18 at 11:23
  • please check my edit – Anelito Mar 16 '18 at 11:39
  • This is asynchronous, if you console log the currentuser inside the `then` callback, it would have value I bet :) I didn't notice that at first ;) – AT82 Mar 16 '18 at 11:43
  • https://stackoverflow.com/questions/43055706/how-do-i-return-the-response-from-an-observable-http-async-call-in-angular2 – AT82 Mar 16 '18 at 11:43

0 Answers0