2017-06-22 47 views
0

我正在尝试制定Auth服务。 我使用这个:如何从angular2服务中的服务构造函数中获取值

@Injectable() 
export class AuthService { 

    authState: any = null; 

    constructor(private afAuth: AngularFireAuth, 
       private db: AngularFireDatabase, 
       private router:Router) { 

      this.afAuth.authState.subscribe((auth) => { 
       this.authState = auth; 

      }); 
      } 

    // Returns true if user is logged in 
    get authenticated(): boolean { 
    return this.authState !== null; 
    } 

的认证()函数不断给我假的,即使用户登录

当我在构造函数中CONSOLE.LOG的authState(this.authState)。 ,我得到一个值,但在构造函数外,this.authState为null。我究竟做错了什么?

+0

您是如何使用该服务的?我的意思是你是否宣称它是应用程序级别或组件级别的提供者。你能分享访问认证功能的组件代码吗? –

+0

订阅方法是异步的。如果您在订阅被解雇之前调用身份验证方法,您将会失败。 –

+0

@BunyaminCoskuner,解决这个问题的方法是什么? –

回答

0

更好的方法是将有单独的函数

authenticated(): Observable<User> { 
    return this.afAuth.authState; 
    } 

然后在你的组件,你可以订阅这个方法,就像你在你的服务构造

编辑做到了!

+0

[ts]类型'Observable '不能指定为'boolean'类型。 –

+0

我只是忘了改变返回类型;]现在试试 –

0

为什么你需要复杂的事情

在你的组件,你所需要的值做到这一点

authState : boolean; 

constructor(private afAuth: AngularFireAuth) { 

      this.afAuth.authState.subscribe((auth) => { 
       this.authState = (auth !== null) ? true : false; 

      }); 
      } 
0

您可以使用APP_INITIALIZER等待异步操作complete.Please检查下面的代码:

AuthService.ts

@Injectable() 
    export class AuthService { 
     authState: any = null; 
    constructor(private afAuth: AngularFireAuth, 
      private db: AngularFireDatabase, 
      private router:Router) { 

     } 
    loadValue(){ 
     return new Promise((resolve, reject) => { 
      this.afAuth.authState.subscribe((auth) => { 
       this.authState = auth; 
       resolve(true); 
      }); 
     }); 
    } 
    // Returns true if user is logged in 
get authenticated(): boolean { 
    return this.authState !== null; 
} 
} 

app.module.ts

import { NgModule, APP_INITIALIZER } from '@angular/core'; 

@NgModule({ 
    //... 
    providers: [AuthService, 
    { 
     provide: APP_INITIALIZER, 
     useFactory: (authService: AuthService) =>() => authService.loadValue(), 
     deps: [AuthService], 
     multi: true 
    }] 
    ///.... 
}) 

希望它可以帮助!

相关问题