Search code examples
ionic-frameworkdeviceaccess-tokenandroid-8.0-oreocordova-plugin-fcm

How do we get android token on ionic 4?


Hello i'm using fcm ionic native plugin, its working well with android 7 and below but on android 8 Oreo and above it can't get the device token, what could be the problem?


Solution

  • You can use the code below and hope it works out for you:

    export interface AuthResponseData {
      kind: string;
      idToken: string;
      email: string;
      refreshToken: string;
      localId: string;
      expiresIn: string;
      registered?: boolean;
    }
    
    export class AuthService implements OnDestroy {
      private _user = new BehaviorSubject<User>(null);
    
      get token() {
        return this._user.asObservable().pipe(
          map(user => {
            if (user) {
              return user.token;
            } else {
              return false;
            }
          })
        );
      }
    
      constructor(private http: HttpClient) { }
    
      signup(email: string, password: string) {
        return this.http
          .post<AuthResponseData>(
            `https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=${yourAPIKey}`,
            { email, password, returnSecureToken: true })
          .pipe(tap(this.setUserData.bind(this)));
      }
    
      login(email: string, password: string) {
        return this.http
          .post<AuthResponseData>(
            `https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=${yourAPIKey}`,
            { email, password, returnSecureToken: true })
          .pipe(tap(this.setUserData.bind(this)));
      }
    
      private setUserData(userData: AuthResponseData) {
        const expirationTime = new Date(new Date().getTime() + +userData.expiresIn * 1000);
        const user = new User(userData.localId, userData.email, userData.idToken, expirationTime);
        this._user.next(user);
        this.storeAuthData(userData.localId, userData.idToken, expirationTime.toISOString(), userData.email);
      }
    
      private storeAuthData(userId: string, token: string, tokenExpirationDate: string, email: string) {
        const data = JSON.stringify({ userId, token, tokenExpirationDate, email });
        Plugins.Storage.set({ key: 'authData', value: data });
      }
    }
    

    And you can use this link for more information