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

时间:2018-09-03 14:42:42

标签: html angular typescript

我正在尝试在用户登录时隐藏元素(按钮等)。

这是我目前所拥有的:

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()"应该在用户登录时隐藏我的按钮。但这行不通... 有人有解决方案吗?

非常感谢您!

3 个答案:

答案 0 :(得分:2)

请勿在模板内使用函数调用,因为您拥有名称为 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>

答案 1 :(得分:2)

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

如我所见,您使用 currentUser 设置了令牌,但是在isLoggedIn方法中,您仅检查 auth_token

所以尝试一下,

isLoggedIn() {

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

答案 2 :(得分:0)

您组件中的方法必须有一个返回值

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

因此,您可以使用以下方法:

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

或变量:

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