无法编写正确的代码以订阅可观察对象?

时间:2018-08-24 03:01:58

标签: angular

下面是我的代码,请告诉我哪里错了?

import { Component } from '@angular/core';
import { AngularFireAuth } from 'angularfire2/auth';
import * as firebase from 'firebase';
import { Observable } from 'rxjs/Observable';
@Component({
  selector: 'bs-navbar',
  templateUrl: './bs-navbar.component.html',
  styleUrls: ['./bs-navbar.component.css']
})
export class BsNavbarComponent {
user:Observable<firebase.User>
  constructor(private afAuth :AngularFireAuth) 
  {
    afAuth.authState.subscribe(user => this.user = user);
   }

 logout(){
   this.afAuth.auth.signOut();
 }

}

我只是在构造函数内部的代码上出错了?

1 个答案:

答案 0 :(得分:2)

您已将用户键入为user:Observable<firebase.User>,但是通过在订阅中设置用户,它不再是Observable。相反,您应该将类​​型更改为user: firebase.User

user: firebase.User;

constructor(private afAuth: AngularFireAuth) 
{
    afAuth.authState.subscribe(user => this.user = user);
}