简体   繁体   中英

Undefined value from local storage promise. Ionic 2+ / Angular 4.3

I'm able to get the value for the token after logging in because I'm passing in the values for the username and password from a function. On the next page, I'm not passing in those values. Which makes sense as to why I'm getting null - this was when I wasn't wrapping the token returns in the promise. When I wrap the token values in the promise as viewed below, I get this error ERROR TypeError: Cannot read property 'then' of undefined, the token is undefined This is because I havn't logged in with the user credentials I need to generate the token, therefore it's not present or undefined. How would I go about calling the function until the user has logged in. Assuming I won't get null back when I make the call to the second page because like I mentioned above, I wrapped my storage promise returns. Thanks!

Auth.ts

login(userName: string, password: string, route: string = null): any {
    this.logout(false);

    this.doLogin(userName, password)
      .subscribe(response => {
        let token:string = JSON.stringify(response.access_token);
        this.storage.set('token', token);

      });
  }

getToken() :any{
  this.storage.get('token').then((val) => {
        this.accessToken = val;

         if(this.accessToken == null){
              return '0'
         }
            else{
                return "Bearer " + this.accessToken.replace(/["]+/g, '')
            }
    })
}

component.ts

login(){
this.authService.login(this.account.username, this.account.password)
}

Interceptor.ts

 intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {


        let access = this.auth.getToken()

        const authReq = req.clone({
                setHeaders: {
                Authorization: access
                }
        });

    return next.handle(authReq)
  }

Thanks!

Return statement inside the promise method won't work. The storage.get() is a promise which is an async function so value return will not work here. You either need to pass a callback function to the getToken method and invoke it inside the then() function or has to write the intercept logic inside then() function of get method in Interceptor.ts.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM