简体   繁体   中英

How check if user is logged in and change routerlink value

I have follow tutoriel on Angular 7 and firebase authentification but i search to know how check if user is already logged in and change routerlink value with if else condition on my view.

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 && 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']);
        })
    }
}

and

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 && num < 5) {
      this.fixed = false;
      }
    }
}

and

  <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>

actualy, only one condition working, but no find the if else condition , where and how implement it for my navigation condition.

Regard

so i will find one way for solved my problem.

first: add authService in my nav component.ts like this.

 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 && num < 5) { this.fixed = false; } } } 

after that, i need to go to my html component and use ngIf and ng-template for create if else condition for switch my li element like this.

  <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> 

So hope that will help ! but if you have other way for do the same, post as comment !

Regard

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM