我正在进行身份验证,该项目可以正常运行并连接到Firebase中的数据库,因为当我需要从项目中检索数据时,当我尝试使用正确的电子邮件和密码登录时,该项目包含了部分内容错误:
错误:发生了网络错误(例如超时,连接中断或主机不可达)。
loginAdminService:
import { Injectable } from '@angular/core';
import { AngularFireDatabase } from 'angularfire2/database';
import { AngularFireAuth } from "@angular/fire/auth";
import * as fireBase from 'firebase';
@Injectable({
providedIn: 'root'
})
export class LoginAdminserviceService {
isAuth: boolean;
constructor(private angularFireAuth: AngularFireAuth,loginDatabase: AngularFireDatabase) {
}
async login(email: string, password: string) {
return new Promise(
(resolve,reject)=>{
fireBase.auth().signInWithEmailAndPassword(email,password).then(
()=>{
this.isAuth = true;
resolve();
},
(error)=>{
this.isAuth = false;
reject(error);
}
)
}
)
}
async logout() {
return await this.angularFireAuth.auth.signOut();
}
isUserLoggedIn() {
return JSON.parse(localStorage.getItem('user'));
}
}
身份验证组件:
import { Component, OnInit } from '@angular/core';
import { LoginAdminserviceService } from '../services/login-adminservice.service';
import { Route, Router } from '@angular/router';
@Component({
selector: 'app-authentication',
templateUrl: './authentication.component.html',
styleUrls: ['./authentication.component.css']
})
export class AuthenticationComponent implements OnInit {
constructor(private route:Router , public loginServiceasAdmin : LoginAdminserviceService) { }
ngOnInit() {
}
async loginAdmin(email:string,password:string){
this.loginServiceasAdmin.login(email,password).then(
()=>{
alert('Bienvenue '+email);
this.route.navigate(['/listreclamation']);
},
(error)=>{
console.log('Pas de connexion '+error);
alert('Votre compte est incorrect');
});
}
}
html页面:
<form>
Email:<input type="text" #email><br>
Password:<input type="password" #password><br>
<button type="submit" (click)="loginAdmin(email.value,password.value)">Login as Admin</button>
<button type="submit" (click)="this.loginServiceasAdmin.logout()">Logout</button>
</form>
答案 0 :(得分:0)
简单示例,登录服务应如下所示:
export class AuthService {
user$: Observable<firebase.User>
constructor(private afAuth: AngularFireAuth) {
this.user$ = this.syncUser()
}
// function trigered once are listen when user is logged in.
syncUser() {
return this.afAuth.authState.pipe(
switchMap(user => {
if(user){
return of(user)
} else {
return of(null)
}
})
)
}
// return is not necesery you can allways listen in real time user$ variable.
async signInWith(credentials: IdCredentials) {
const result = await this.afAuth.auth.signInWithEmailAndPassword(credentials.email, credentials.password)
return result
}
}