我是angular和firebase的新手,仅在成功进行身份验证后尝试将用户数据添加到表中-如果正确登录,表将显示数据,否则,您将无法看到此数据。我尝试在AuthService中进行简单的Firebase登录和注销:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { AngularFireAuth } from '@angular/fire/auth';
import { Router } from '@angular/router';
import * as firebase from 'firebase/app';
@Injectable({
providedIn: 'root',
})
export class AuthService {
constructor(private router: Router, private fireAuth: AngularFireAuth) {}
onLogin(email: string, password: string) {
firebase
.auth()
.signInWithEmailAndPassword(email, password)
.then(function () {
console.log('Succes');
})
.catch(function (error) {
console.log(error);
});
}
async onLogout() {
try {
await firebase.auth().signOut();
this.router.navigate(['./']);
} catch (error) {
console.log(error);
}
}
}
这是我的UserService,负责在表中显示用户:
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
import { take } from 'rxjs/operators';
import { User } from 'src/app/models/user.model';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root',
})
export class UserService {
constructor(private http: HttpClient) {}
fetchUsers() {
let result = new Subject<User[]>();
this.http
.get('https://fir-login-1416c.firebaseio.com/users.json')
.subscribe((users) => {
let usersAr = Object.keys(users).map((id) => new User(users[id]));
result.next(usersAr);
});
return result.pipe(take(1));
}
addUser(user: User) {
let postData: User = user;
this.http
.post<{ name: string }>(
'https://fir-login-1416c.firebaseio.com/users.json',
postData,
{
observe: 'response',
}
)
.subscribe(
(responseData) => {
console.log(responseData.body.name);
},
(error) => {
console.log(error);
}
);
this.fetchUsers();
}
deleteUser() {
// Later
}
}
我的firebase数据库规则如下:
{
"rules": {
".write": "auth !== null",
".read": "auth !== null"
}
}
但是,当我使用正确的数据登录并导航到包含用户表的页面时,就会发现探查表和控制台显示为空 this errors。 验证似乎根本不起作用,或者我做错了什么。 如果您对此有任何建议,请给我:)谢谢!
答案 0 :(得分:2)
您需要随请求发送某种授权标头。否则,数据库不会真正知道您已通过身份验证。
我建议不仅将AngularFire用于身份验证,而且还将其用于获取数据。