我正在尝试使用angular和firebase构建一个Web应用程序,它具有登录表单和主页。
问题是当我登录时,它会按照预期将我带到主页,但是在点击任何链接或甚至刷新主页时,它会将我记录下来!
我的login.component.ts
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { User } from '../_helpers/user';
import { AuthService } from '../auth.service'
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
user: User;
constructor(
private authService: AuthService,
private route: ActivatedRoute,
private router: Router) {
}
ngOnInit() {
this.user = new User("","");
if( this.authService.isLoggedIn() )
this.router.navigate(['home']);
}
onSubmit() {
this.authService.login(this.user.email, this.user.password);
this.user.email = this.user.password = '';
this.router.navigate(['home']);
}
}

my home.component.ts
import { Component, OnInit } from '@angular/core';
import { Database } from '../_helpers/database';
import { AuthGuard } from '../_helpers/authGuard';
import { Observable } from 'rxjs/Observable';
import { AuthService } from '../auth.service';
import { ActivatedRoute, Router } from '@angular/router';
import { AngularFireDatabase } from 'angularfire2/database';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
database : Database;
carsObservable: Observable<any[]>;
constructor(
private db: AngularFireDatabase,
private authService: AuthService,
private route: ActivatedRoute,
private router: Router) {}
ngOnInit() {
if( !this.authService.isLoggedIn() ){
this.router.navigate(['login']);
return;
}
this.database = new Database(this.db, this.route, this.router);
this.carsObservable = this.database.getCars();
}
}
&#13;
和auth.service.ts
import { Injectable } from '@angular/core';
import { AngularFireAuth } from 'angularfire2/auth';
import * as firebase from 'firebase/app';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class AuthService {
user: Observable<firebase.User>;
static result = false;
constructor(private firebaseAuth: AngularFireAuth) {
this.user = firebaseAuth.authState;
}
login(email: string, password: string) {
this.firebaseAuth.auth.signInWithEmailAndPassword(email, password)
.then(value => {
console.log('signedIn');
})
.catch(err => {
console.log('NotYet: ',err.message);
});
}
isLoggedIn() : boolean{
this.firebaseAuth.auth.onAuthStateChanged(function(user) {
if(user){
AuthService.result = true;
}else{
AuthService.result = false;
}
});
return AuthService.result;
}
/*logout() : void{
this.firebaseAuth.auth.signOut();
}*/
}
&#13;