简体   繁体   English

Angular 8 *ngIf 未在导航栏中正确反映 UI

[英]Angular 8 *ngIf does not reflect the UI properly in the navigation bar

I am trying to integrate bootstrap@4 into an Angular 8 application so to make it fully-responsive.我正在尝试将 bootstrap@4 集成到 Angular 8 应用程序中,以使其完全响应。

If the user is not registered (signed up) or is not logged-in, some elements in the nav bar should be hidden (logout btn or link) and if he is logged in others should (login btn or link).如果用户未注册(注册)或未登录,则导航栏中的某些元素应隐藏(注销 btn 或链接),如果他已登录,则应隐藏其他元素(登录 btn 或链接)。

To make the case more clear, below are snippets of code where the header.ts file include a verification whether the user object exists or not.为了更清楚地说明情况,下面是代码片段,其中 header.ts 文件包含用户对象是否存在的验证。 This is done through a service injection in the.ts file constructor.这是通过 .ts 文件构造函数中的服务注入完成的。 Retrospectively, the service makes a call to a firebase REST API to check for the validity of the authentication.回顾过去,该服务调用 firebase REST API 以检查身份验证的有效性。

After a valid authentication, the login btn or link should go away and a logout element should appear instead.有效身份验证后,登录 btn 或链接应消失,而应出​​现注销元素。

This is partially working.这是部分工作。 I navigate away from the login interface (form) into another component (services) but the navbar does not update respectively.我从登录界面(表单)导航到另一个组件(服务),但导航栏没有分别更新。 I still have the same ui before logging in.登录前我仍然拥有相同的用户界面。

Any hints or suggestions how to solve the issue?任何提示或建议如何解决问题? Is it because of bootstrap@4?是因为 bootstrap@4 吗? (There are no errors in the console) (控制台没有错误)

Thanks in advance提前致谢

 import { Component, OnInit, OnDestroy } from '@angular/core'; import { AuthService } from 'src/app/auth/auth.service'; import { Subscription } from 'rxjs'; @Component({ selector: 'app-header', templateUrl: './header.component.html', styleUrls: ['./header.component.css'] }) export class HeaderComponent implements OnInit, OnDestroy { isAuthenticated = false; private userSub: Subscription; constructor(private authservice: AuthService) { } ngOnInit() { this.userSub = this.authservice.user.subscribe(user =>{ this.isAuthenticated = !!user; } ); } ngOnDestroy(){ this.userSub.unsubscribe(); } }
 <nav class="navbar navbar-expand-md navbar-light bg-light sticky-top"> <div class="container-fluid"> <a class="navbar-brand" href="#"><img src="assets/img/logo.png"></a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarResponsive"> <ul class="navbar-nav ml-auto"> <li> <a class="nav-link" routerLink="/home" routerLinkActive="active" style="cursor: pointer;">Home</a> </li> <li> <a class="nav-link" routerLink="/about" routerLinkActive="active" style="cursor: pointer;">About</a> </li> <li routerLinkActive="active"> <a class="nav-link" routerLink="/services" style="cursor: pointer;">Services</a> </li> <li routerLinkActive="active"> <a class="nav-link" routerLink="/team" style="cursor: pointer;">Team</a> </li> <li routerLinkActive="active" *ngIf="!isAuthenticated"> <a class="nav-link" routerLink="/auth" style="cursor: pointer;" > Login | Sign up </a> </li> <li routerLinkActive="active" *ngIf="isAuthenticated"> <a class="nav-link" routerLink="/auth" style="cursor: pointer;" > Logout </a> </li> </ul> </div> </div> </nav>

This is weird.这很奇怪。

@kurt Hamilton, below is the sevrvice @kurt Hamilton,下面是服务

 import { Component } from '@angular/core'; import { NgForm } from '@angular/forms'; import { Observable } from 'rxjs'; import { AuthService } from './auth.service'; import { AuthResponseData} from'./auth.service' import { Router } from '@angular/router'; @Component({ selector: 'app-auth', templateUrl: './auth.component.html', styleUrls: ['./auth.component.css'] }) export class AuthComponent { isLoginMode= true; error: string = null; 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>; if(this.isLoginMode){ authObs = this.authservice.login(email, password); }else{ authObs = this.authservice.signUp(email, password); } authObs.subscribe( response =>{ console.log(response); this.router.navigate(['/services']); }, errorMessage =>{ console.log(errorMessage); this.error = errorMessage; } ); form.reset(); } }

Thank you very much, but yet I do not get the point.非常感谢,但我还是不明白。 Please let me know if you have a solution!如果您有解决方案,请告诉我! Thanks again.再次感谢。

@Fmerco, I do subscribe to observables in the auth.component.ts (included below) @Fmerco,我确实订阅了 auth.component.ts 中的 observables(包括在下面)

 import { Injectable } from '@angular/core'; import { HttpClient, HttpErrorResponse } from '@angular/common/http'; import {catchError, tap} from 'rxjs/operators' import { throwError, Subject } from 'rxjs'; import { User } from './user.model'; 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>( 'https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=[key-omitted]', { 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>( 'https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=[key-omitted]', { email: email, password: password, returnSecureToken: true } ).pipe(catchError (this.handleError)); } 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(errorRes: HttpErrorResponse){ let errorMessage = 'An unknown error occured'; if(!errorRes.error || !errorRes.error.error){ return throwError(errorMessage); } switch(errorRes.error.error.message){ case 'EMAIL_EXISTS': errorMessage = 'This email already exists' break; case 'EMAIL_NOT_FOUND': errorMessage = 'This email does not exist' break; case 'INVALID_PASSWORD': errorMessage= 'Incorrect password' break; } return throwError(errorMessage); } }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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