4

In a library that im using there is the method, getToken which is used in the example like:

getApplicationToken() {
    window.FirebasePlugin.getToken(function(token) {
      console.log('Got FCM token: ' + token);
    }, function(error) {
      console.log('Failed to get FCM token', error);
    });
  }

What I want is to create a method that returns the token itself. What I tried:

async getApplicationTokenString(): Promise<string> {
    return window.FirebasePlugin.getToken();
}

And calling it by:

let firebaseToken = '';
this.fireBaseService.getApplicationTokenString().then(function(resolveOutput) {
   firebaseToken = resolveOutput;
  }, function(rejectOutput) {
    console.log(rejectOutput);
  });

However I get: Firebase token: so I have no value. However when I call getApplicationToken the fcm token is logged.

How should I pass the value given by a promise async?

Sven van den Boogaart
  • 11,833
  • 21
  • 86
  • 169
  • 1
    I don think this is a duplicate as my question is mostly about how to do it in angular . the linked answer does not give me an example of how to implement it in angular. Im exactly trying to do myself (see example) what they are doing in the linked answer but the syntax is different. – Sven van den Boogaart Nov 27 '19 at 15:52

1 Answers1

3

Wrap the code in Promise and call resolver when token is available

 getApplicationToken() {
        return new Promise((reslove, reject) => {
            window.FirebasePlugin.getToken(function(token) {
                console.log('Got FCM token: ' + token);
                resolve(token);
            }, function(error) {
            console.log('Failed to get FCM token', error);
            });
        });
      }

add a await operator to wait for a Promise

 async processApplicationTokenString(): Promise<string> {
    let token =  await this.getApplicationToken();
    console.log(token); // your token available here
    this.firebaseToken = token;
    console.log('This line not execute until until promise resolve');
  }
Saurabh Yadav
  • 3,303
  • 1
  • 10
  • 20