ngIf не обновляет мою переменную isAuthenticated - PullRequest
0 голосов
/ 22 января 2020

Правильно, поэтому у меня есть компонент заголовка (navbar), который содержит следующий шаблон:

это мой nav.component. html

image

В этой панели навигации есть несколько кнопок, которые должны быть видны только аутентифицированным пользователям ...

my nav.component.ts

import { Component, OnInit, OnDestroy, Injectable } from '@angular/core';
    import { AuthService } from '../auth/auth.service';
    import { Subscription } from 'rxjs';

@Component({
  selector: 'app-nav',
  templateUrl: './nav.component.html',
  styleUrls: ['./nav.component.css']
})


export class NavComponent implements OnInit {

  isAuthenticated = false;

  private userSub: Subscription;

  constructor(private authService: AuthService) {


  }

  ngOnInit() {

    this.userSub = this.authService.user.subscribe( user => {

       this.isAuthenticated = !!user;

       console.log(!user);
       console.log(!!user);

    });

  }

  ngOnDestroy(){

    this.userSub.unsubscribe();

  }

}

, хотя я могу видеть значения isAuthenticated переменные меняются, но я не вижу никаких изменений в панели навигации ...

мой файл auth.service.ts


import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { throwError, Subject } from 'rxjs';
import { User } from './user.model';
import { catchError , tap } from 'rxjs/operators';



export interface AuthResponseData {

  idToken: string,
  email: string,
  refreshToken: string,
  expiresIn: string,
  localId: string

  registered?: boolean;

}

@Injectable({
  providedIn: 'root'
})

export class AuthService {



 user = new Subject<User>();




  constructor(private http: HttpClient) {

  }

  signup(email: string, password: string) {

    return this.http.post<AuthResponseData>('-----',

      {
        email: email,
        password: password,
        returnSecureToken: true
      }

    ).pipe(catchError(this.handleError) , tap(resData => {


         this.handleAuthentication(resData.email,resData.localId, resData.idToken, +resData.expiresIn,);

    }));

  }


  login(email: string, password: string) {

    return this.http.post<AuthResponseData>('---------',

      {

        email: email,
        password: password,
        returnSecureToken: true
      }


    ).pipe(catchError(this.handleError),  tap(resData => {


     this.handleAuthentication(resData.email,resData.localId, resData.idToken, +resData.expiresIn,);

 }));

  }



  private handleAuthentication(email: string, userid: string, token: string, expiresIn: number){

    const expirationdate= new Date(new Date().getTime()+ expiresIn * 1000);

    const user = new User(email, userid , token, expirationdate);


    this.user.next(user);


  }

  private handleError(errRes: HttpErrorResponse) {

    let errorMessage = "An unknown error occured!";

    if (!errRes.error || !errRes.error.error) {

      return throwError(errorMessage);
    }

    switch (errRes.error.error.message) {
      case 'EMAIL_EXISTS':
        errorMessage = "This email exists already";
        break;
      case 'EMAIL_NOT_FOUND':
        errorMessage="This email does not exists.";
        break;
      case 'INVALID_PASSWORD': 
        errorMessage="Invalid Password";
        break;
    }


    return throwError(errorMessage);

  }


}

это auth.component.ts


import { Component, OnInit } from '@angular/core';
import { NgForm, Form } from '@angular/forms';
import { Router } from '@angular/router';
import { Observable } from 'rxjs';
import { AuthService, AuthResponseData } from './auth.service';

@Component({
  selector: 'app-auth',
  templateUrl: './auth.component.html',
  styleUrls: ['./auth.component.css']
})
export class AuthComponent implements OnInit {


  isLoginMode = true;

  isLoading = false;
  error = null;
  ngForm;


  constructor(private authservice: AuthService, private router: Router) { }

  onSwitchMode() {

    this.isLoginMode = !this.isLoginMode;

  }


  onsubmit(form: NgForm) {


    if (!form.valid) {

      return;

    }



    const email = form.value.email;
    const password = form.value.password;


    let authobs: Observable<AuthResponseData>;

    this.isLoading = true;

    if (this.isLoginMode) {
      authobs=this.authservice.login(email,password);
    }
    else {

      authobs=this.authservice.signup(email, password);





    }
    // console.log(form.value);



    authobs.subscribe(resData => {

      console.log(resData);

      this.isLoading = false;
      this.router.navigate(['/now']);

    }, errorMessage => {

      console.log(errorMessage);

      this.error = errorMessage;

      // switch(errorRes.error.error.message){
      //   case 'EMAIL_EXISTS':
      //     this.error="This email exists already";
      // }
      this.isLoading = false;
      // this.error="An error occurred";

    });


    form.reset();

  }
  // onSubmit(form: NgForm) {

  //   console.log(form.value);
  //   form.reset();
  // }




  ngOnInit() {

  }

}

...