我只想验证用户是否登录,所以我在auth.service中实现方法getAuth(),我在navbar.component中的方法ngOnInit()上调用它,但是我有一个错误,我找不到任何解决方案
这是我的auth.service的代码
import { Observable } from 'rxjs';
import { AngularFireAuth } from 'angularfire2/auth';
import { Injectable } from '@angular/core';
@Injectable()
export class AuthService {
constructor(
public afAuth: AngularFireAuth,
) { }
login(email:string, password:string){
return new Promise((resolve,reject) => {
this.afAuth.auth.signInWithEmailAndPassword(email,password)
.then(userData => resolve(userData),
err=>reject(err));
});
}
getAuth(){
return this.afAuth.authState.map(auth => auth); -->
}
logout(){
this.afAuth.auth.signOut();
}
}
**我在navbar.components **
中的ngOnInit()上调用了该函数import { Observable } from 'rxjs';
import { AuthService } from './../../services/auth.service';
import { Router } from '@angular/router';
import { FlashMessagesService } from 'angular2-flash-messages';
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-navbar',
templateUrl: './navbar.component.html',
styleUrls: ['./navbar.component.css']
})
export class NavbarComponent implements OnInit {
isLoggedIn: boolean = true;
loggedInUser:string;
showRegister:boolean;
constructor(
private authService: AuthService,
private route: Router,
private flashMessagesService : FlashMessagesService
) { }
ngOnInit() {
this.authService.getAuth().subscribe(auth => {
if (auth){
this.isLoggedIn = true;
this.loggedInUser = auth.email;
}else{
this.isLoggedIn = false;
}
});
}
onLogoutClick(){
this.authService.logout();
this.flashMessagesService.show('You are logged out', {cssClass:'alert-success', timeout:4000});
this.route.navigate(['/login']);
}
}
错误
ERROR TypeError: this.afAuth.authState.map is not a function
at AuthService.getAuth (auth.service.ts:24)
at NavbarComponent.ngOnInit (navbar.component.ts:26)
at checkAndUpdateDirectiveInline (core.js:12369)
at checkAndUpdateNodeInline (core.js:13893)
at checkAndUpdateNode (core.js:13836)
at debugCheckAndUpdateNode (core.js:14729)
at debugCheckDirectivesFn (core.js:14670)
at Object.eval [as updateDirectives] (AppComponent.html:1)
at Object.debugUpdateDirectives [as updateDirectives] (core.js:14655)
at checkAndUpdateView (core.js:13802)