typescript - Firebase + Typescript,无法从用户对象中获取 accessToken?

标签 typescript firebase react-native firebase-authentication

在我的 MobX 商店中,我似乎无法从 Firebase 登录中获取 accessToken。不过,数据显然在那里。它适用于 React-Native。

示例:

class GlobalStore {

    @observable loggedIn: boolean;

    @observable user: any;

    @action firebaseStatup = () => {

        firebase.initializeApp({
            apiKey: "somestring",
            authDomain: "app.firebaseapp.com",
            databaseURL: "https://app.firebaseio.com",
            projectId: "app",
            storageBucket: "app.appspot.com",
            messagingSenderId: "1234
        });
        firebase.auth().onAuthStateChanged((user) => {
            this.loggedIn = !!user;
            if (user) {
                this.user = firebase.auth().currentUser;
                console.log(this.user); // Returns an Object that has property stsTokenManager.accessToken which is the JWT?
                console.log(this.user.stsTokenManager.accessToken)
            }
        })
    };

console.log(this.user); 生成一个包含所有用户信息的大对象。在 stsTokenManager.accessToken 上,存在 token 。

如果我想直接访问该属性,我会返回:

undefined is not an object (evaluating '_this.user.stsTokenManager.accessToken')

如何获取明明存在的accessToken

最佳答案

问题是 user 返回了一个 promise 。我想把它保存到 AsyncStorage,所以是这样的:

// ... Firebase stuff

    firebase.auth().onAuthStateChanged((user) => {
        this.loggedIn = !!user;
        if (user) {
            this.user = firebase.auth().currentUser;
            user.getIdToken()
                .then(token => this.saveTokenToStorage(token))

        }
    });

@action async saveTokenToStorage(token: string) {
    try {
        await AsyncStorage.setItem('authentication', token);
    } catch (error) {
        // Error saving data
    }
};

关于typescript - Firebase + Typescript,无法从用户对象中获取 accessToken?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48152802/

相关文章:

typescript - Angular2 ag-grid 数据源不工作

javascript - Firebase 检索返回未定义/对象对象

swift - 用于显示来自 Firebase 的子值计数的 UIButton 标签

reactjs - 在 React Native Expo 上加载自定义字体会出现错误

reactjs - 无法使用react-native-snap-carousel

javascript - 在 React Native 中从 AsyncStorage 获取值后渲染组件

angular - 仅运行一次 Angular 更改检测并停止检测该组件的更改

typescript - 错误 : Illegal reassignment to import

javascript - 如何推送设置了特定状态的数据?

java - 使用 Android 登录 Google 连接时出现错误