我们如何在 ionic 4 上获得 android 令牌?

How do we get android token on ionic 4?

你好,我正在使用 fcm 离子本机插件,它在 android 7 及以下版本上运行良好,但在 android 8 Oreo 及更高版本上它无法获取设备令牌,这可能是什么问题?

您可以使用下面的代码,希望它对您有用:

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 });
  }
}

您可以使用此 link 了解更多信息