Я хочу создать приложение с аутентификацией ioni c с помощью firebase, и каждый пользователь получает профиль, который может сделать это, но у пользователя есть проблема, чтобы получить только свой профиль
import { Profile } from "./../shared/Profile";
import { Injectable } from "@angular/core";
import { Observable } from "rxjs";
import {
AngularFirestore,
AngularFirestoreCollection,
DocumentReference,
} from "@angular/fire/firestore";
import { map, take } from "rxjs/operators";
@Injectable({
providedIn: "root",
})
export class ProfileService {
private Profiles: Observable<Profile[]>;
private ProfileCollection: AngularFirestoreCollection<Profile>;
constructor(private afs: AngularFirestore) {
this.ProfileCollection = this.afs.collection<Profile>("Profiles");
this.Profiles = this.ProfileCollection.snapshotChanges().pipe(
map((actions) => {
return actions.map((a) => {
const data = a.payload.doc.data();
const id = a.payload.doc.id;
return { id, ...data };
});
})
);
}
getProfiles(): Observable<Profile[]> {
return this.Profiles;
}
getProfile(id: string): Observable<Profile> {
return this.ProfileCollection.doc<Profile>(id)
.valueChanges()
.pipe(
take(1),
map((Profile) => {
Profile.id = id;
return Profile;
})
);
}
addProfile(Profile: Profile): Promise<DocumentReference> {
return this.ProfileCollection.add(Profile);
}
updateProfile(Profile: Profile): Promise<void> {
return this.ProfileCollection.doc(Profile.id).update({
nom: Profile.nom,
prenom: Profile.prenom,
cycle: Profile.cycle,
matier: Profile.matier,
region: Profile.region,
deriction: Profile.deriction,
ecoel: Profile.ecole,
phone: Profile.phone,
mail: Profile.mail,
});
}
deleteProfile(id: string): Promise<void> {
return this.ProfileCollection.doc(id).delete();
}
}
для страницы профиля это вкладка только для созданного в первый раз после регистрации, но tab2 для отображения всего информационного профиля логина пользователя
export class Tab1Page {
constructor(private fbService: ProfileService,
private toastCtrl: ToastController,private router: Router) {}
profile: Profile = {
nom: 'd',
phone: 'd',
mail: 'd',
typ:'null',
createdAt: new Date().getTime(),
};
addProfile(){
this.fbService.addProfile(this.profile).then(() => {
this.router.navigateByUrl('/tabs/tab2');
console.log('profile ajouter '+this.profile.nom);
}, err => {
});
}
, но теперь как получить профиль пользователя в tab2
import { Injectable, NgZone } from '@angular/core';
// --------------
import { User } from './../shared/auth';
import { auth } from 'firebase/app';
import { Router } from "@angular/router";
import { AngularFirestore, AngularFirestoreDocument } from '@angular/fire/firestore';
import { AngularFireAuth } from "@angular/fire/auth";
import { firebase } from '@firebase/app';
import '@firebase/auth';
@Injectable({
providedIn: 'root'
})
export class AuthenticationService {
userData: any;
constructor(
public afStore: AngularFirestore,
public ngFireAuth: AngularFireAuth,
public router: Router,
public ngZone: NgZone
) {
this.ngFireAuth.authState.subscribe(user => {
if (user) {
this.userData = user;
localStorage.setItem('user', JSON.stringify(this.userData));
JSON.parse(localStorage.getItem('user'));
} else {
localStorage.setItem('user', null);
JSON.parse(localStorage.getItem('user'));
}
})
}
// Login in with email/password
SignIn(email, password) {
return this.ngFireAuth.signInWithEmailAndPassword(email, password)
}
// Register user with email/password
RegisterUser(email, password) {
return this.ngFireAuth.createUserWithEmailAndPassword(email, password)
}
// Email verification when new user register
SendVerificationMail() {
console.log("hyyh");
}
// Recover password
PasswordRecover(passwordResetEmail) {
return this.ngFireAuth.sendPasswordResetEmail(passwordResetEmail)
.then(() => {
window.alert('Password reset email has been sent, please check your inbox.');
}).catch((error) => {
window.alert(error)
})
}
// Returns true when user is looged in
get isLoggedIn(): boolean {
const user = JSON.parse(localStorage.getItem('user'));
return (user !== null && user.emailVerified !== false) ? true : false;
}
// Returns true when user's email is verified
get isEmailVerified(): boolean {
const user = JSON.parse(localStorage.getItem('user'));
return (user.emailVerified !== false) ? true : false;
}
// Sign in with Gmail
GoogleAuth() {
return this.AuthLogin(new auth.GoogleAuthProvider());
}
// Auth providers
AuthLogin(provider) {
return this.ngFireAuth.signInWithPopup(provider)
.then((result) => {
this.ngZone.run(() => {
this.router.navigate(['dashboard']);
})
this.SetUserData(result.user);
}).catch((error) => {
window.alert(error)
})
}
// Store user in localStorage
SetUserData(user) {
const userRef: AngularFirestoreDocument<any> = this.afStore.doc(`users/${user.uid}`);
const userData: User = {
uid: user.uid,
email: user.email,
displayName: user.displayName,
photoURL: user.photoURL,
emailVerified: user.emailVerified
}
return userRef.set(userData, {
merge: true
})
}
// Sign-out
SignOut() {
return this.ngFireAuth.signOut().then(() => {
localStorage.removeItem('user');
this.router.navigate(['login']);
})
}
}