Angular2 - 我的服务是null

时间:2018-01-21 12:04:09

标签: angular

import { Injectable } from '@angular/core';

@Injectable()
export class UserProfileProvider {
    private uid: string;

    constructor() {
    }
    function1() {}

}

以上是我的服务。我在app.module.ts中的提供程序中有它:

  providers: [
    .
    .
    .
    UserProfileProvider,
  ]

在app.component.ts中我正在注射它:

constructor(public userProfile: UserProfileProvider)

但是userProfile为null:

platform.ready().then(() => {
  statusBar.styleDefault();
  splashScreen.hide();
  if(this.userProfile == null) {
        // true
        console.log("userProfile == null");
    }
});

更新1:但home.ts上的userProfile不为空

1 个答案:

答案 0 :(得分:1)

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

  this.subscription = this.afAuth.authState
    .catch((error: any) => {
      console.log("google login failed, error: ", error);
      this.rootPage = LoginPage;
      this.userProfile = null;
      return Observable.empty();
    })
    .subscribe((user: firebase.User) => {
      if (user && user.uid) {
        this.rootPage = HomePage;
        this.events.publish('user:signedIn', user.uid);
        if(this.userProfile == null) {
          console.log("userProfile == null");

        } else {
          this.userProfile.setUid(user.uid);
        }
        // this.userProfile.setUid(user.uid);
      } else {
        this.rootPage = LoginPage;
        // this.userProfile = null; <== culprit
      }
    });
});

在清除浏览器缓存时,用户将为null,然后我将this.userProfile设置为null,然后当我尝试登录时,它将为null。