Весь код страницы
import { Component, OnInit } from '@angular/core';
import { AngularFirestore, DocumentReference } from '@angular/fire/firestore';
import { Observable, of, from } from 'rxjs';
import { IGreetAllUser } from '../models/igreetAllUser';
import { User } from 'src/app/auth/models/user';
import { flatMap, switchMap } from 'rxjs/operators';
import { Router } from '@angular/router';
import { AutheroizeService } from 'src/app/auth/services/autheroize.service';
import { AngularFireAuth } from '@angular/fire/auth';
interface GreetAll {
admin: boolean;
country: string;
firstName: string;
lastName: string;
userEmail: string;
userId: string;
userType: string;
}
interface RootObject {
greetAll: GreetAll;
}
@Component({
selector: 'app-test',
templateUrl: './test.component.html',
styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit {
userData;
user$: Observable<User>;
greetAllUsersInServer = [];
singleUserFromServer = [];
localUser;
userEmail;
currentUser;
savedUser;
myUser: IGreetAllUser;
myUserAfterStringConversion;
private userRef: DocumentReference;
greetAllUsersInServerINBDE: Observable<any[]>;
constructor(private afAuth: AngularFireAuth,
private db: AngularFirestore,
private afs: AngularFirestore,
private _router: Router,
private _authorizeService: AutheroizeService) { }
ngOnInit() {
console.log('Test Component.ts working now')
this.fetchUser().catch(error => console.log(error));
}
-> Мне нужна помощь в этой функции
Я не могу направить пользователя на соответствующую страницу, не обновив страницу. Я хочу, чтобы это происходило без обновления.
async fetchUser() {
try {
const localStorageUser = await this.checkLocalStorage();
if (localStorageUser == null ){
const settingUserFromServer = await this.serverUser$();
const localStorageUser = await this.checkLocalStorage();
const userEmail = await localStorageUser.email;
const userType = await this.selectedClient(userEmail);
const last = await this.directToRespectivePage(userType);
console.log('second last' + userType);
} else {
const userEmail = await localStorageUser.email;
const userType = await this.selectedClient(userEmail);
const last = await this.directToRespectivePage(userType);
console.log('last' + userType);
}
} catch (error) {
return { name: 'Default' }
}
}
> вызов сервера для поиска типа пользователя
serverUser$() {
this.afAuth.authState.subscribe(user => {
if (user) {
this.userData = user;
localStorage.setItem('user', JSON.stringify(this.userData));
const userServer = JSON.stringify(localStorage.getItem('user'));
return userServer;
} else {
localStorage.setItem('user', null);
}
})
}
> проверка локального хранилища для типа пользователя
checkLocalStorage() {
if (localStorage.getItem("user") === null) {
return null
} else {
const user = JSON.parse(localStorage.getItem('user'));
console.log(user);
return user;
}
}
> наконец, обнаружив тип пользователя
selectedClient(email: string) {
if (email == null) {
return null
} else {
const snapshotResult = this.db.collection('greetAll', q =>
q.where('greetAll.userEmail', '==', email)
.limit(1))
.snapshotChanges()
.pipe(flatMap(greetAllUsersInServerINBDE => greetAllUsersInServerINBDE));
snapshotResult.subscribe(doc => {
this.myUser = <IGreetAllUser>doc.payload.doc.data();
this.userRef = doc.payload.doc.ref;
if (this.myUser.greetAll.userEmail != null) {
return this.myUser.greetAll.userType;
} else {
return null
}
});
}
}
> направляя пользователя на его собственную страницу
directToRespectivePage(utype: string) {
console.log('direct to respective page has received value ' + utype);
if (utype == "student") {
this._router.navigate(['wlecomeStudent']);
} else if (utype == "faculty") {
this._router.navigate(['welcomeFaculty']);
} else if (utype == "admin") {
this._router.navigate(['welcomeAdmin']);
} else if (utype == null) {
this._router.navigate(['greetAllUsers']);
}
}
-> проверяя, существует ли пользователь
checkIfUserExists() {
this._authorizeService.getUser();
this.localUser = JSON.parse(localStorage.getItem('user'));
this.db.collection(`greetAll`, q => q.where(`greetAll.userEmail`, `==`, this.localUser.email)
).snapshotChanges().subscribe(serverItems => {
this.singleUserFromServer;
serverItems.forEach(a => {
let item: any = a.payload.doc.data();
item.id = a.payload.doc.id;
this.singleUserFromServer.push(item);
})
if (this.singleUserFromServer.length > 0) {
this.currentUser = this.singleUserFromServer;
this.selectedClient(this.savedUser)
} else {
this._router.navigate(['greetAllUsers']);
}
})
}
}