#javascript #firebase #firebase-authentication #angular7
#javascript #firebase #firebase-аутентификация #angular7
Вопрос:
Я следую инструкциям по аутентификации Angular 7 и firebase, но я ищу, чтобы узнать, как проверить, вошел ли пользователь в систему, и изменить значение routerlink с условием if else на мой взгляд.
import { Injectable, NgZone } from '@angular/core';
import { User } from "../services/user";
import { auth } from 'firebase/app';
import { AngularFireAuth } from "@angular/fire/auth";
import { AngularFirestore, AngularFirestoreDocument } from '@angular/fire/firestore';
import { Router } from "@angular/router";
@Injectable({
providedIn:'root'
})
export class AuthService {
userData: any; // Save logged in user data
constructor(
public afs: AngularFirestore, // Inject Firestore service
public afAuth: AngularFireAuth, // Inject Firebase auth service
public router: Router,
public ngZone: NgZone // NgZone service to remove outside scope warning
) {
this.afAuth.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'));
}
})
}
// Sign in with email/password
SignIn(email, password){
return this.afAuth.auth.signInWithEmailAndPassword(email, password)
.then((result) => {
this.ngZone.run(() => {
this.router.navigate(['dashboard']);
});
this.SetUserData(result.user);
}).catch((error) =>{
window.alert(error.message)
})
}
// Sign up with email/password
SignUp(email, password) {
return this.afAuth.auth.createUserWithEmailAndPassword(email, password)
.then((result) => {
/* Call the SendVerificaitonMail() function when new user sign
up and returns promise */
this.SendVerificationMail();
this.SetUserData(result.user);
}).catch((error) => {
window.alert(error.message)
})
}
// Send email verfificaiton when new user sign up
SendVerificationMail(){
return this.afAuth.auth.currentUser.sendEmailVerification()
.then(() => {
this.router.navigate(['verify-email-address']);
})
}
// Reset Forggot password
ForgotPassword(passwordResetEmail){
window.alert('forgot password');
return this.afAuth.auth.sendPasswordResetEmail(passwordResetEmail)
.then(() => {
window.alert('Password reset email sent, check your inbox.');
}).catch((error) => {
window.alert(error);
})
}
// Returns true when user is looged in and email is verified
get isLoggedIn(): boolean {
const user = JSON.parse(localStorage.getItem('user'));
return (user !== null amp;amp; user.emailVerified !== false) ?true : false;
}
// Sign in with Google
GoogleAuth(){
return this.AuthLogin(new auth.GoogleAuthProvider());
}
// Auth logic to run auth providers
AuthLogin(provider){
return this.afAuth.auth.signInWithPopup(provider)
.then((result) => {
this.ngZone.run(() => {
this.router.navigate(['dashboard']);
})
this.SetUserData(result.user);
}).catch((error) => {
window.alert(error)
})
}
/* Setting up user data when sign in with username/password,
sign up with username/password and sign in with social auth
provider in Firestore database using AngularFirestore AngularFirestoreDocument service */
SetUserData(user){
const userRef: AngularFirestoreDocument<any> = this.afs.doc('user/${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.afAuth.auth.signOut().then(() => {
localStorage.removeItem('user');
this.router.navigate(['home']);
})
}
}
и
import { Component, OnInit, Inject, HostListener } from '@angular/core';
import { DOCUMENT } from "@angular/platform-browser";
@Component({
moduleId: module.id,
selector: 'main-nav',
templateUrl: './nav.component.html',
styleUrls: ['./nav.component.css']
})
export class NavComponent implements OnInit {
public fixed: boolean = false;
constructor(@Inject(DOCUMENT) private document: Document) {}
ngOnInit() { }
@HostListener("window:scroll", [])
onWindowScroll() {
let num = this.document.body.scrollTop;
if ( num > 50 ) {
this.fixed = true;
}else if (this.fixed amp;amp; num < 5) {
this.fixed = false;
}
}
}
и
<div id="top-header">
<div class="container">
<div class="th-left col-sm-6 clearfix">
<ul class="social-icons standard">
<li class="facebook">
<a href="" target="_blank">
<i class="fa-facebook"></i>
<i class="fa-facebook"></i>
</a>
</li>
<li class="linkedin">
<a href="https://www.linkedin.com/in/terausquin/" target="_blank">
<i class="fa-linkedin"></i>
<i class="fa-linkedin"></i>
</a>
</li>
<li class="viadeo">
<a href="http://www.viadeo.com/p/0022ertvt67wfnub" target="_blank">
<i class="fa-viadeo"></i>
<i class="fa-viadeo"></i>
</a>
</li>
</ul>
</div>
<div class="th-right col-sm-6 clearfix">
<nav class="std-menu top-header-menu">
<ul class="menu">
<li *ngIf="isLoggedIn"><a [routerLink]="['/dashboard']">Dashboard</a></li>
<li *ngIf="!isLoggedIn"><a [routerLink]="['/sign-in']">Logged In</a></li>
<li class="parent aux-languages"><a href="#"><span class="language name">English</span></a>
<ul id="header-languages" class="sub-menu">
<li>
<a href="#"><span class="language name">German</span></a>
</li>
<li>
<div class="current-language">
<span class="language name">French</span>
</div>
</li>
<li>
<a href="#"><span class="language name">English</span></a>
</li>
</ul>
</li>
</ul>
</nav>
</div>
</div>
</div>
<nav class="navbar navbar-expand-md navbar-light">
<div class="container">
<a class="navbar-brand" href="#"><img src="../../assets/images/logo-v2-screen.png" /></a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarsExample07" aria-controls="navbarsExample07" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarsExample07">
<ul class="navbar-nav ml-auto">
<li class="nav-item" [routerLinkActive]="['active']" [routerLinkActiveOptions]="{exact:true}">
<a class="nav-link" [routerLink]="['/home']">Homepage<span class="nav-line"></span></a>
</li>
<li class="nav-item" [routerLinkActive]="['active']" [routerLinkActiveOptions]="{exact:true}">
<a class="nav-link" [routerLink]="['/portfolio']">Portefolio<span class="nav-line"></span></a>
</li>
<li class="nav-item dropdown" [routerLinkActive]="['active']" [routerLinkActiveOptions]="{exact:true}">
<a class="nav-link dropdown-toggle" href="" id="dropdown07" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Prestations<span class="nav-line"></span></a>
<div class="dropdown-menu" aria-labelledby="dropdown07">
<a class="dropdown-item" [routerLink]="['/confection']">Confection Site Web</a>
<a class="dropdown-item" [routerLink]="['/cours']">Cours Informatique et Télécom</a>
<a class="dropdown-item" [routerLink]="['/depannage']">Dépannage Informatique et Télécom</a>
</div>
</li>
<li class="nav-item" [routerLinkActive]="['active']" [routerLinkActiveOptions]="{exact:true}">
<a class="nav-link" [routerLink]="['/apropos']">A-propos<span class="nav-line"></span></a>
</li>
<!--<li class="nav-item" [routerLinkActive]="['active']" [routerLinkActiveOptions]="{exact:true}">
<a class="nav-link" [routerLink]="['/blog']">Blog<span class="nav-line"></span></a>
</li>-->
<li class="nav-item" [routerLinkActive]="['active']" [routerLinkActiveOptions]="{exact:true}">
<a class="nav-link" [routerLink]="['/contact']">Contactez-moi<span class="nav-line"></span></a>
</li>
</ul>
</div>
</div>
</nav>
на самом деле работает только одно условие, но не найти условие if else, где и как его реализовать для моего условия навигации.
Внимание
Ответ №1:
поэтому я найду один способ решить мою проблему.
во-первых: добавьте AuthService в мой nav component.ts следующим образом.
import { Component, OnInit, Inject, HostListener } from '@angular/core';
import { DOCUMENT } from "@angular/platform-browser";
import { AuthService } from '../shared/services/auth.service';
@Component({
moduleId: module.id,
selector: 'main-nav',
templateUrl: './nav.component.html',
styleUrls: ['./nav.component.css']
})
export class NavComponent implements OnInit {
public fixed: boolean = false;
constructor(
@Inject(DOCUMENT)
private document: Document,
private authService: AuthService
) {}
ngOnInit() { }
@HostListener("window:scroll", [])
onWindowScroll() {
let num = this.document.body.scrollTop;
if ( num > 50 ) {
this.fixed = true;
}else if (this.fixed amp;amp; num < 5) {
this.fixed = false;
}
}
}
после этого мне нужно перейти к моему html-компоненту и использовать ngIf и ng-template для создания условия if else для переключения моего элемента li следующим образом.
<li *ngIf="authService.isLoggedIn; else showlogin"><a [routerLink]="['/dashboard']">Dashboard</a></li>
<ng-template #showlogin>
<li><a [routerLink]="['/sign-in']">Logged In</a></li>
</ng-template>
Надеюсь, это поможет! но если у вас есть другой способ сделать то же самое, отправьте комментарий!
Внимание