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

时间:2019-07-07 17:54:17

标签: angular typescript angular7 behaviorsubject angular-changedetection

我仅在登录后引用了以下链接来启用注销按钮 https://stackblitz.com/edit/angular-login-hide-navbar-ngif

我只想在用户登录后才在导航栏中显示“注销”,我正在通过从“身份验证服务”中调用“ this.authservice.isUserLoggedIn”并将其分配给变量来验证用户是否登录并在“注销”链接附近写入ngif条件。我已经使用BehaviourSubject来获取当前状态。但是我不知道为什么代码无法正常工作,并且总是返回false,因此即使用户登录后也无法启用“注销”链接

我有header.component.ts

export class CommonheaderComponent implements OnInit {

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

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

下面是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 => {
  })    
 }
}

我具有以下身份验证服务

    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();
      } 
    }

我在哪里做错了。或为此的解决方案/替代方案。请帮忙!

很久以来我一直坚持下去

2 个答案:

答案 0 :(得分:0)

像这样更改模板后可以尝试:

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

请注意,async管道将可观察值解包。

您共享的stackblitz示例中的通知-使用async管道解开了可观察值-

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

答案 1 :(得分:0)

对于您的最后一条评论,是由于重新初始化了服务,并且您的可观察项已被重置,所以发生了这种情况。将此添加到您的构造函数

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

这对我有用。