当用户登录时,我试图隐藏元素(按钮等...)。

这是我目前所拥有的:

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

这个:*ngIf="!authService.isLoggedIn()" 应该在用户登录时隐藏我的按钮。但它不起作用...
有人有解决方案吗?

非常感谢你!!

最佳答案

我认为问题出在您的 isLoggedIn() 方法中,

正如我所看到的,您使用 currentUser 设置 token ,但在 isLoggedIn 方法中,您只检查 auth_token

所以试试这个

isLoggedIn() {

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

关于html - Angular:用户登录时隐藏元素,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52151935/

10-12 06:34