AngularFire Observables/Subscribe - 不在同一范围内设置类变量 [英] AngularFire Observables / Subscribe - Not Setting Class Variable in Same Scope

查看:27
本文介绍了AngularFire Observables/Subscribe - 不在同一范围内设置类变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Firebase 构建一个 Ionic 应用程序,因此使用 AngularFire2.在 Angularfire2 中,您可以进行身份​​验证,但它是一个 observable,必须订阅才能获取用户对象.问题是我似乎无法设置 this.user = user 因为它看起来不像 .subscribe 在同一范围内.

I'm building an Ionic app using Firebase, and therefore AngularFire2. In Angularfire2 you can authenticate, but it's an observable and have to subscribe to get the user object. The problem is that I can't seem to set this.user = user because it doesn't seem like .subscribe is in the same scope.

这是一个例子,我有一个 auth.ts 和一个 app.component.ts.在我的服务中,我进行身份验证,

Here's an example, I have a auth.ts and an app.component.ts. In my service, I authenticate,

auth.ts

export class AuthService {

// user: Observable<firebase.User>;
user: object = {
    displayName: null,
    email: null,
    emailVerified: null,
    photoUrl: null,
    uid: null
};

constructor(private facebook: Facebook,
            private googlePlus: GooglePlus,
            private platform: Platform,
            private afAuth: AngularFireAuth) {

    // this.user = afAuth.authState;
    afAuth.authState.subscribe((user: firebase.User) => {

        if (!user) {
            this.user = null;
            return;
        }
        this.user =  {
            displayName: user.displayName,
            email: user.email,
            emailVerified: user.emailVerified,
            photoUrl: user.photoURL,
            uid: user.uid
        }
    });

}

在我的 app.component.ts 中:

and in my app.component.ts:

app.component.ts

export class MytApp {

rootPage: any = TabsPage;
signinPage = SigninPage;
@ViewChild('nav') nav: NavController;

userProfile: any = null;

constructor(private platform: Platform, 
            private menuCtrl: MenuController,
            private statusBar: StatusBar, 
            private splashScreen: SplashScreen,
            private authService: AuthService) {

    // this.authService.user.subscribe((user: firebase.User) => {
        // var user = authService.user;
        // if (user) {
        //  this.userProfile = user;
        //  this.onLoad(TabsPage);
        // } else {
        //  this.userProfile = null;
        //  this.onLoad(SigninPage);
        // }
    // });

    platform.ready().then(() => {
        // Okay, so the platform is ready and our plugins are available.
        // Here you can do any higher level native things you might need.
        statusBar.styleDefault();
        splashScreen.hide();

        var user = authService.user; /* HERE */
        console.log(user);
        if (user) {
            this.userProfile = user;
            this.onLoad(TabsPage);
        } else {
            this.userProfile = null;
            this.onLoad(SigninPage);
        }
    });
}

}

如您所见,在 var user = authService.user; 之后,我运行 console.log(user); 并且我得到的是:

As you can see, right after var user = authService.user; I run console.log(user); and what I get is:

console.log(user);

   displayName: null,
   email: null,
   emailVerified: null,
   photoUrl: null,
   uid: null

我使用用户对象来定位 Firebase 中的用户数据,所以这是必要的.问题是用户对象没有更新,就像它超出了 afAuth.authState.subscribe((user: firebase.User) => {} 的范围".

I use the user object for targeting user data in Firebase, so it's necessary. The problem is that the user object isn't updated, it's like it's out of the "scope" of the afAuth.authState.subscribe((user: firebase.User) => {}.

知道我如何无法订阅,而只是简单地获取用户对象,或者从订阅中提取数据以便我可以轻松地从其他组件中检索它(因为它是一项服务)?请帮忙!

Any idea how I can not subscribe, and just simply get the user object, or maybe extract the data from the subscribe so that I can easily retrieve it (because it's a service) from other components? Please help!

推荐答案

您不能在您的服务中执行 subscribe().你想要做的是返回一个Observable,让组件自己处理Observable,而不是在服务中.这是因为您的 API 调用是异步的,并且您的组件无法等待 http 调用的解析.

You can't do a subscribe() in your service. What you want to do, is to return an Observable, and let the components handle the Observables themselves, and not in the service. Reason for this is because your API call is asynchronous and your components cannot wait for the resolve of the http calls.

您可以做的是通过将您的 AngularFireAuth 映射到您想要的对象来返回一个 Observable.

What you can do is you can return an Observable by mapping your AngularFireAuth to an object that you desire.

export class AuthService {
    public user: Observable<any>; //this can be any type you wish
    constructor(private facebook: Facebook,
                private googlePlus: GooglePlus,
                private platform: Platform,
                private afAuth: AngularFireAuth) {

        this.user =
            afAuth.authState.map((user: firebase.User) => {
                if (!user) {
                    return null;
                }
                else return {
                    displayName: user.displayName,
                    email: user.email,
                    emailVerified: user.emailVerified,
                    photoUrl: user.photoURL,
                    uid: user.uid
                }
            });
    }
}

现在,您可以在任何其他组件中订阅您的 AuthService.user:

Now, you can subscribe to your AuthService.user in any other component:

export class MytApp {

    rootPage: any = TabsPage;
    signinPage = SigninPage;
    @ViewChild('nav') nav: NavController;

    userProfile: any = null;

    constructor(private platform: Platform,
                private menuCtrl: MenuController,
                private statusBar: StatusBar,
                private splashScreen: SplashScreen,
                private authService: AuthService) {


        platform.ready().then(() => {
            // Okay, so the platform is ready and our plugins are available.
            // Here you can do any higher level native things you might need.
            statusBar.styleDefault();
            splashScreen.hide();
            //subscribe to AuthService
            authService.subscribe(user => {
                console.log(user);
                if (user) {
                    this.userProfile = user;
                    this.onLoad(TabsPage);
                } else {
                    this.userProfile = null;
                    this.onLoad(SigninPage);
                }
            })
        });
    }
}

这篇关于AngularFire Observables/Subscribe - 不在同一范围内设置类变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆