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

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

问题描述

我正在使用Firebase和AngularFire2构建Ionic应用程序.在Angularfire2中,您可以进行身份​​验证,但这是可观察的,必须订阅才能获取用户对象.问题是我似乎无法设置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,让组件自己处理Observables,而不是在服务中处理.这样做的原因是因为您的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/订阅-在相同范围内未设置类变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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