Ionic local storage not getting the data












0















I am trying to get the token that I stored using the ionic storage and store it in a global variable public token = ''. But every time I access it using this.token the value doesn't change.



import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Storage } from '@ionic/storage';

const TOKEN_KEY = 'access_token';

@Injectable()
export class ContactProvider {

public url = 'myapi-link';
public token = '';


constructor(
private storage: Storage,
private http: HttpClient
) {

}

loadToken(){

this.storage.get(TOKEN_KEY).then((token)=>{
this.token = token;
console.log(this.token);
});

}

setHeaders(default_content_type = 'application/json'){

let headers = new HttpHeaders();
headers = headers.set('Content-Type', default_content_type)
.set('Authorization', 'Bearer ' + this.token)
return headers;

}

getData(type){

this.loadToken();
let headers = this.setHeaders();
return this.http.get(this.url + type, {headers: headers});

}

}


when calling the this.setHeaders(), the this.token does not change.










share|improve this question





























    0















    I am trying to get the token that I stored using the ionic storage and store it in a global variable public token = ''. But every time I access it using this.token the value doesn't change.



    import { HttpClient, HttpHeaders } from '@angular/common/http';
    import { Injectable } from '@angular/core';
    import { Storage } from '@ionic/storage';

    const TOKEN_KEY = 'access_token';

    @Injectable()
    export class ContactProvider {

    public url = 'myapi-link';
    public token = '';


    constructor(
    private storage: Storage,
    private http: HttpClient
    ) {

    }

    loadToken(){

    this.storage.get(TOKEN_KEY).then((token)=>{
    this.token = token;
    console.log(this.token);
    });

    }

    setHeaders(default_content_type = 'application/json'){

    let headers = new HttpHeaders();
    headers = headers.set('Content-Type', default_content_type)
    .set('Authorization', 'Bearer ' + this.token)
    return headers;

    }

    getData(type){

    this.loadToken();
    let headers = this.setHeaders();
    return this.http.get(this.url + type, {headers: headers});

    }

    }


    when calling the this.setHeaders(), the this.token does not change.










    share|improve this question



























      0












      0








      0








      I am trying to get the token that I stored using the ionic storage and store it in a global variable public token = ''. But every time I access it using this.token the value doesn't change.



      import { HttpClient, HttpHeaders } from '@angular/common/http';
      import { Injectable } from '@angular/core';
      import { Storage } from '@ionic/storage';

      const TOKEN_KEY = 'access_token';

      @Injectable()
      export class ContactProvider {

      public url = 'myapi-link';
      public token = '';


      constructor(
      private storage: Storage,
      private http: HttpClient
      ) {

      }

      loadToken(){

      this.storage.get(TOKEN_KEY).then((token)=>{
      this.token = token;
      console.log(this.token);
      });

      }

      setHeaders(default_content_type = 'application/json'){

      let headers = new HttpHeaders();
      headers = headers.set('Content-Type', default_content_type)
      .set('Authorization', 'Bearer ' + this.token)
      return headers;

      }

      getData(type){

      this.loadToken();
      let headers = this.setHeaders();
      return this.http.get(this.url + type, {headers: headers});

      }

      }


      when calling the this.setHeaders(), the this.token does not change.










      share|improve this question
















      I am trying to get the token that I stored using the ionic storage and store it in a global variable public token = ''. But every time I access it using this.token the value doesn't change.



      import { HttpClient, HttpHeaders } from '@angular/common/http';
      import { Injectable } from '@angular/core';
      import { Storage } from '@ionic/storage';

      const TOKEN_KEY = 'access_token';

      @Injectable()
      export class ContactProvider {

      public url = 'myapi-link';
      public token = '';


      constructor(
      private storage: Storage,
      private http: HttpClient
      ) {

      }

      loadToken(){

      this.storage.get(TOKEN_KEY).then((token)=>{
      this.token = token;
      console.log(this.token);
      });

      }

      setHeaders(default_content_type = 'application/json'){

      let headers = new HttpHeaders();
      headers = headers.set('Content-Type', default_content_type)
      .set('Authorization', 'Bearer ' + this.token)
      return headers;

      }

      getData(type){

      this.loadToken();
      let headers = this.setHeaders();
      return this.http.get(this.url + type, {headers: headers});

      }

      }


      when calling the this.setHeaders(), the this.token does not change.







      angular ionic3 ionic-storage






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Jan 2 at 8:49









      Tushar Walzade

      2,28031633




      2,28031633










      asked Jan 2 at 2:31









      Remarc BalisiRemarc Balisi

      475




      475
























          2 Answers
          2






          active

          oldest

          votes


















          1














          Like Others have pointed out, you need to understand how promises work.
          Here is something how:
          1: LoadToken needs to return a promise:



          loadToken(){
          return this.storage.get(TOKEN_KEY);
          }


          Note the return key word which will return the promise returned by storage.get()



          2: consume that promise and wait for it to complete before you carry on:



          async getData(type){
          this.token = await this.loadToken();
          let headers = this.setHeaders();
          return this.http.get(this.url + type, {headers: headers});
          }


          Note the async key word in front of the getData method name which indicates you will be waiting for promises to complete within it.
          then the await key word which will make sure the rest of the code after it will only execute when the promise resolves.



          Since a promise can also be rejected, you need to do the following :



          async getData(type){
          try {
          this.token = await this.loadToken();
          let headers = this.setHeaders();
          return this.http.get(this.url + type, {headers: headers});
          } catch (error) {
          //Handle your error here
          }
          }





          share|improve this answer































            0














            Call the setHeaders within the loadToken as it returns the data asynchronously,



            loadToken(){
            this.storage.get(TOKEN_KEY).then((token)=>{
            this.token = token;
            console.log(this.token);
            this.headers = this.setHeaders();
            });
            }





            share|improve this answer
























            • is there a way to wait for the token to totally load it from the storage?

              – Remarc Balisi
              Jan 2 at 2:47











            • use loadToken().then

              – Sajeetharan
              Jan 2 at 4:44











            • You'll need to return a promise from loadToken() for @Sajeetharan's suggestion above

              – Tushar Walzade
              Jan 2 at 6:47













            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54000581%2fionic-local-storage-not-getting-the-data%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            1














            Like Others have pointed out, you need to understand how promises work.
            Here is something how:
            1: LoadToken needs to return a promise:



            loadToken(){
            return this.storage.get(TOKEN_KEY);
            }


            Note the return key word which will return the promise returned by storage.get()



            2: consume that promise and wait for it to complete before you carry on:



            async getData(type){
            this.token = await this.loadToken();
            let headers = this.setHeaders();
            return this.http.get(this.url + type, {headers: headers});
            }


            Note the async key word in front of the getData method name which indicates you will be waiting for promises to complete within it.
            then the await key word which will make sure the rest of the code after it will only execute when the promise resolves.



            Since a promise can also be rejected, you need to do the following :



            async getData(type){
            try {
            this.token = await this.loadToken();
            let headers = this.setHeaders();
            return this.http.get(this.url + type, {headers: headers});
            } catch (error) {
            //Handle your error here
            }
            }





            share|improve this answer




























              1














              Like Others have pointed out, you need to understand how promises work.
              Here is something how:
              1: LoadToken needs to return a promise:



              loadToken(){
              return this.storage.get(TOKEN_KEY);
              }


              Note the return key word which will return the promise returned by storage.get()



              2: consume that promise and wait for it to complete before you carry on:



              async getData(type){
              this.token = await this.loadToken();
              let headers = this.setHeaders();
              return this.http.get(this.url + type, {headers: headers});
              }


              Note the async key word in front of the getData method name which indicates you will be waiting for promises to complete within it.
              then the await key word which will make sure the rest of the code after it will only execute when the promise resolves.



              Since a promise can also be rejected, you need to do the following :



              async getData(type){
              try {
              this.token = await this.loadToken();
              let headers = this.setHeaders();
              return this.http.get(this.url + type, {headers: headers});
              } catch (error) {
              //Handle your error here
              }
              }





              share|improve this answer


























                1












                1








                1







                Like Others have pointed out, you need to understand how promises work.
                Here is something how:
                1: LoadToken needs to return a promise:



                loadToken(){
                return this.storage.get(TOKEN_KEY);
                }


                Note the return key word which will return the promise returned by storage.get()



                2: consume that promise and wait for it to complete before you carry on:



                async getData(type){
                this.token = await this.loadToken();
                let headers = this.setHeaders();
                return this.http.get(this.url + type, {headers: headers});
                }


                Note the async key word in front of the getData method name which indicates you will be waiting for promises to complete within it.
                then the await key word which will make sure the rest of the code after it will only execute when the promise resolves.



                Since a promise can also be rejected, you need to do the following :



                async getData(type){
                try {
                this.token = await this.loadToken();
                let headers = this.setHeaders();
                return this.http.get(this.url + type, {headers: headers});
                } catch (error) {
                //Handle your error here
                }
                }





                share|improve this answer













                Like Others have pointed out, you need to understand how promises work.
                Here is something how:
                1: LoadToken needs to return a promise:



                loadToken(){
                return this.storage.get(TOKEN_KEY);
                }


                Note the return key word which will return the promise returned by storage.get()



                2: consume that promise and wait for it to complete before you carry on:



                async getData(type){
                this.token = await this.loadToken();
                let headers = this.setHeaders();
                return this.http.get(this.url + type, {headers: headers});
                }


                Note the async key word in front of the getData method name which indicates you will be waiting for promises to complete within it.
                then the await key word which will make sure the rest of the code after it will only execute when the promise resolves.



                Since a promise can also be rejected, you need to do the following :



                async getData(type){
                try {
                this.token = await this.loadToken();
                let headers = this.setHeaders();
                return this.http.get(this.url + type, {headers: headers});
                } catch (error) {
                //Handle your error here
                }
                }






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Jan 2 at 11:13









                MehdiMehdi

                1,067814




                1,067814

























                    0














                    Call the setHeaders within the loadToken as it returns the data asynchronously,



                    loadToken(){
                    this.storage.get(TOKEN_KEY).then((token)=>{
                    this.token = token;
                    console.log(this.token);
                    this.headers = this.setHeaders();
                    });
                    }





                    share|improve this answer
























                    • is there a way to wait for the token to totally load it from the storage?

                      – Remarc Balisi
                      Jan 2 at 2:47











                    • use loadToken().then

                      – Sajeetharan
                      Jan 2 at 4:44











                    • You'll need to return a promise from loadToken() for @Sajeetharan's suggestion above

                      – Tushar Walzade
                      Jan 2 at 6:47


















                    0














                    Call the setHeaders within the loadToken as it returns the data asynchronously,



                    loadToken(){
                    this.storage.get(TOKEN_KEY).then((token)=>{
                    this.token = token;
                    console.log(this.token);
                    this.headers = this.setHeaders();
                    });
                    }





                    share|improve this answer
























                    • is there a way to wait for the token to totally load it from the storage?

                      – Remarc Balisi
                      Jan 2 at 2:47











                    • use loadToken().then

                      – Sajeetharan
                      Jan 2 at 4:44











                    • You'll need to return a promise from loadToken() for @Sajeetharan's suggestion above

                      – Tushar Walzade
                      Jan 2 at 6:47
















                    0












                    0








                    0







                    Call the setHeaders within the loadToken as it returns the data asynchronously,



                    loadToken(){
                    this.storage.get(TOKEN_KEY).then((token)=>{
                    this.token = token;
                    console.log(this.token);
                    this.headers = this.setHeaders();
                    });
                    }





                    share|improve this answer













                    Call the setHeaders within the loadToken as it returns the data asynchronously,



                    loadToken(){
                    this.storage.get(TOKEN_KEY).then((token)=>{
                    this.token = token;
                    console.log(this.token);
                    this.headers = this.setHeaders();
                    });
                    }






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Jan 2 at 2:38









                    SajeetharanSajeetharan

                    123k30178237




                    123k30178237













                    • is there a way to wait for the token to totally load it from the storage?

                      – Remarc Balisi
                      Jan 2 at 2:47











                    • use loadToken().then

                      – Sajeetharan
                      Jan 2 at 4:44











                    • You'll need to return a promise from loadToken() for @Sajeetharan's suggestion above

                      – Tushar Walzade
                      Jan 2 at 6:47





















                    • is there a way to wait for the token to totally load it from the storage?

                      – Remarc Balisi
                      Jan 2 at 2:47











                    • use loadToken().then

                      – Sajeetharan
                      Jan 2 at 4:44











                    • You'll need to return a promise from loadToken() for @Sajeetharan's suggestion above

                      – Tushar Walzade
                      Jan 2 at 6:47



















                    is there a way to wait for the token to totally load it from the storage?

                    – Remarc Balisi
                    Jan 2 at 2:47





                    is there a way to wait for the token to totally load it from the storage?

                    – Remarc Balisi
                    Jan 2 at 2:47













                    use loadToken().then

                    – Sajeetharan
                    Jan 2 at 4:44





                    use loadToken().then

                    – Sajeetharan
                    Jan 2 at 4:44













                    You'll need to return a promise from loadToken() for @Sajeetharan's suggestion above

                    – Tushar Walzade
                    Jan 2 at 6:47







                    You'll need to return a promise from loadToken() for @Sajeetharan's suggestion above

                    – Tushar Walzade
                    Jan 2 at 6:47




















                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54000581%2fionic-local-storage-not-getting-the-data%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Mossoró

                    Error while reading .h5 file using the rhdf5 package in R

                    Pushsharp Apns notification error: 'InvalidToken'