简体   繁体   English

角度:用户登录时隐藏元素

[英]Angular: hide element when user is logged in

I'm trying to hide elements (buttons etc...) when the user is logged in. 我正在尝试在用户登录时隐藏元素(按钮等)。

Here is what I've got for the moment: 这是我目前所拥有的:

app.component.ts app.component.ts

import {Component, OnInit} from '@angular/core';
import {TranslateService} from '@ngx-translate/core';
import {first} from 'rxjs/operators';

import {User} from './models/user.model';
import {UserService} from './services/user.service';
import {AuthenticationService} from "./services/authentication.Service";

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent implements OnInit {
  title = 'melanom-web';
  users: User[] = [];
  isAuthenticated: boolean;
  constructor(public authService: AuthenticationService, private translate: TranslateService, private userService: UserService) {
    translate.setDefaultLang('fr');
  }

  ngOnInit() {
    this.userService.getAll().pipe(first()).subscribe(users => {
      this.users = users;
    });
    this.isLoggedIn();
  }

  switchLanguage(language: string) {
    this.translate.use(language);
  }

  Logout() {
    this.authService.logout();
  }
  isLoggedIn() {
    this.isAuthenticated = this.authService.isLoggedIn();
  }
}

app.component.html app.component.html

    <div class='container'>
  <div>
    <button (click)="switchLanguage('fr')"><img src="./src/assets/france.png" class="img-fluid"></button>
    <button (click)="switchLanguage('en')"><img src="./src/assets/uk.png" class="img-fluid"></button>
    <div class="float-right margin-top10">
        <button *ngIf="!authService.isLoggedIn()" type="button" routerLink="/register" class="btn btn-info margin-right">{{ 'Register' | translate }}</button>
        <button *ngIf="!authService.isLoggedIn()" type="button" routerLink="/login" class="btn btn-success">{{ 'Login' | translate }}</button>
    </div>
<div *ngIf="authService.isLoggedIn()">
    Users from secure api end point:
    <ul>
        <li *ngFor="let user of users">{{user.firstName}} {{user.lastName}}</li>
    </ul>
</div>
<p><a [routerLink]="['/login']">Logout</a></p>
  </div>
    <router-outlet></router-outlet>
</div>

authentication.service.ts 身份验证服务

import {environment} from "../../environments/environment";
import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {map} from 'rxjs/operators';

@Injectable({providedIn: 'root'})
export class AuthenticationService {
  isLoggedin: boolean = false;
  constructor(private http: HttpClient) {}

  login(username: string, password: string) {
    return this.http.post<any>(environment.apiUrl + '/users/authenticate', {username, password})
      .pipe(map(user => {
        // login successful if there's a jwt token in the response
        if (user && user.token) {
          // store user details and jwt token in local storage to keep user logged in between page refreshes
          localStorage.setItem('currentUser', JSON.stringify(user));
          this.isLoggedin = true;
        }

        return user;
      }));
  }

  logout() {
    // remove user from local storage to log user out
    localStorage.removeItem('currentUser');
    this.isLoggedin = false;
  }

  isLoggedIn() {
    debugger;
    if (localStorage.getItem("auth_token") == null) {
      this.isLoggedin = false;
      return this.isLoggedin;
    }
    else {
      return true;
    }
  }
}

this: *ngIf="!authService.isLoggedIn()" should hide my buttons when the user is logged. 这: *ngIf="!authService.isLoggedIn()"在用户登录时应隐藏我的按钮。 But it doesn't works... Does someone has a solution? 但这行不通...有人解决方案吗?

Thank you very much!! 非常感谢你!!

Don't use function calls inside template , for that you have a property with name isAuthenticated 不要在template内使用函数调用 ,因为您拥有一个名为isAuthenticated的属性

<div>
    <button *ngIf="!this.isAuthenticated" type="button" routerLink="/register" class="btn btn-info margin-right">{{ 'Register' | translate }}</button>
    <button *ngIf="!this.isAuthenticated" type="button" routerLink="/login" class="btn btn-success">{{ 'Login' | translate }}</button>
</div>
<div *ngIf="this.isAuthenticated">
    Users from secure api end point:
    <ul>
        <li *ngFor="let user of users">{{user.firstName}} {{user.lastName}}</li>
    </ul>
</div>

I think the problem is in your isLoggedIn() method, 我认为问题出在您的isLoggedIn()方法中,

as i can see you set token with currentUser but in isLoggedIn method you are checking only auth_token 如我所见,您使用currentUser设置了令牌,但是在isLoggedIn方法中,您仅检查auth_token

so try this, 所以试试这个

isLoggedIn() {

    if (JSON.parse(localStorage.getItem('currentUser')).auth_token == null) {
      this.isLoggedin = false;
      return this.isLoggedin;
    }
    else {
      return true;
    }
  }

Your method in component must have one return 您组件中的方法必须有一个返回

isLoggedIn() {
    this.isAuthenticated = this.authService.isLoggedIn();
    return this.isAuthenticated;
  }

So, you can use with an method: 因此,可以使用以下方法:

<div *ngIf="isLoggedIn()">
    Users from secure api end point:
    <ul>
        <li *ngFor="let user of users">{{user.firstName}} {{user.lastName}}</li>
    </ul>
</div>

Or variable: 或变量:

<div *ngIf="isAuthenticated">
    Users from secure api end point:
    <ul>
        <li *ngFor="let user of users">{{user.firstName}} {{user.lastName}}</li>
    </ul>
</div>

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

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