简体   繁体   English

仅在Angular 7中登录后启用注销按钮

[英]enable Logout button only after Login in Angular 7

I have refered the below link for enabling the logout button only after login https://stackblitz.com/edit/angular-login-hide-navbar-ngif 我仅在登录https://stackblitz.com/edit/angular-login-hide-navbar-ngif后才引用以下链接来启用注销按钮

I want to display the "logout" in navbar only when user is logged in for which I am verifying if the user is logged in by calling "this.authservice.isUserLoggedIn" from "Authenication service" and assigning it to a variable and writing a ngif condition near "logout" link. 我只想在用户登录后才在导航栏中显示“注销”,我正在通过从“身份验证服务”中调用“ this.authservice.isUserLoggedIn”并将其分配给变量并写入一个来验证用户是否登录“注销”链接附近的ngif条件。 I have used BehaviourSubject to get the current state. 我已经使用BehaviourSubject来获取当前状态。 But I don't know why the code is not working and it is always returning false and hence "logout" link is not enabled even after user is logged in 但是我不知道为什么代码不起作用,并且总是返回false,因此即使用户登录后也无法启用“注销”链接

I have header.component.ts 我有header.component.ts

export class CommonheaderComponent implements OnInit {

  constructor(private authservice : AuthenticationService) { }
  isLoggedIn$ : Observable<boolean>;
  ngOnInit() {
    this.isLoggedIn$ = this.authservice.isUserLoggedIn;
  }
  }

I have the header.component.html as below 我有如下的header.component.html

<ul class="nav navbar-nav">
      <li><a [routerLink]='["/search"]'>Search <span class="slider"></span></a></li>
      <li *ngIf="isLoggedIn"><a (click)="logout()">Logout</a></li>
  </ul>

Below is the login.component.ts 以下是login.component.ts

export class LoginComponent implements OnInit {
  isLoggedIn : Observable<boolean>;

 ngOnInit() {
   this.isLoggedIn = this.authservice.isUserLoggedIn;
   this.loginForm = this.formbuilder.group({
    username : ['', Validators.required],
    password : ['', Validators.required]
  })
 }

}

  onSubmit(){
    this.authservice.login(this.loginForm.value).subscribe(data => {
  })    
 }
}

I have the authentication service as below 我有以下身份验证服务

    import { Injectable } from '@angular/core';
    import { HttpClient, HttpHeaders } from '@angular/common/http';
    import { BehaviorSubject, Observable } from 'rxjs';
    import { map } from 'rxjs/operators';
    import { User } from '../_models/user';
    import { Router } from '@angular/router';

    const httpOptions =  {
      headers : new HttpHeaders({'Content-type' : 'application/json'})
    }

    @Injectable({
      providedIn: 'root'
    })
    export class AuthenticationService {
      private currentUserSubject : BehaviorSubject<User>;
      private currentUser : Observable<User>;
      private loggedIn: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);

      constructor(private http: HttpClient, private router: Router) {
        this.currentUserSubject = new BehaviorSubject<User>(JSON.parse(localStorage.getItem('currentUser')));
        this.currentUser = this.currentUserSubject.asObservable();
      }

      public get currentUserValue(): User{
        return this.currentUserSubject.value;
      }

      public login(user: User):Observable<any>{
        var baseUrl = "http://localhost:3000/";
        return this.http.post<any>(baseUrl+'auth/login', user, httpOptions).pipe(map(user => {
          if(user && user.accesstoken){
            localStorage.setItem('currentUser', JSON.stringify(user));
            this.currentUserSubject.next(user);
            this.loggedIn.next(true);
          }else{
            return false;
          }
          return user;
        }))
      }

      get isUserLoggedIn(){
          return this.loggedIn.asObservable();
      } 
    }

Where did I do the mistake. 我在哪里犯错了。 Or what is the solution / alternate for this. 或为此的解决方案/替代方案。 Please help!! 请帮忙!!

I am stuck with this since long time 很久以来我一直坚持

Can you try after changing your template like this: 您可以像这样更改模板后尝试:

<ul class="nav navbar-nav">
      <li><a [routerLink]='["/search"]'>Search <span class="slider"></span></a></li>
      <li *ngIf="isLoggedIn$ | async"><a (click)="logout()">Logout</a></li>
  </ul>

Notice the async pipe to unwrap the observable value. 注意async管道解包了可观察的值。

Notice in the stackblitz example shared by you - Observable value was unwrapped using async pipe - 请注意,在您共享的stackblitz示例中-可观察的值已使用async管道展开-

<mat-toolbar color="primary" *ngIf="isLoggedIn$ | async as isLoggedIn">

to your last comment, this is happening because the service is being re-initialized and your observable are being reset. 对于您的最后一条评论,这是因为服务正在重新初始化并且您的观察值已被重置。 Add this to your constructor 将此添加到您的构造函数

if(localStorage.getItem('currentUser') != null)
    this.loggedIn.next(true);

This worked for me. 这对我有用。

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

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