Не работает динамическая ссылка на заголовок - PullRequest
0 голосов
/ 08 мая 2019

Я разрабатываю разрешение на основе ролей, где теперь мне нужно отобразить ссылки в заголовке, и оно исходит из базы данных.

После входа в систему мне нужно обновить страницу, чтобы отобразить динамические ссылки.

Я использовал ngx-разрешение и загружал массив разрешений и проверял разрешение.

header.component.ts

import { Component, OnInit, AfterViewInit } from '@angular/core';
import { LoginService } from '../login.service';
import { Router } from '@angular/router';
import { NgxPermissionsService } from 'ngx-permissions';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {
  permissionData = null
  permissionModule = null
  useremail = null
  perm = [];

  constructor(
    private loginApi: LoginService,
    private permissionsService: NgxPermissionsService,
    private http: HttpClient,
    private router: Router,
  ) {
    console.log("Header constuctor")
  }

  ngOnInit() {
    console.log('Header initialized')
    this.useremail = localStorage.getItem('useremail')
    this.perm.push(this.useremail)
    // console.log("User Email", this.useremail)
    this.checkUserPermissions()
  }

  logout() {
    this.loginApi.logout()
    this.router.navigate(['/login'])
  }

  checkUserPermissions() {
    let userID = localStorage.getItem('userid')
    if (userID) {
      this.loginApi.getAuthenticatedUserPermissions(userID).subscribe(res => {
        this.permissionModule = Object.keys(res[0].permissions[0])
        this.permissionData = res
        // ngx permission
        const perm = [];
        perm.push(this.permissionModule)
        this.permissionsService.loadPermissions(perm)
      }, error => {
        console.log(error)
      })
    }
  }

}

header.component.html

<div *ngIf="permissionModule?.length">
        <div *ngxPermissionsOnly="dashboard">
          <a routerLink="/barcharts">Dashboard</a>
        </div>
        <div *ngxPermissionsOnly="product management">
          <a routerLink="/productmanagement">Product Management</a>
        </div>
        <div *ngxPermissionsOnly="app userlisting">
          <a routerLink="/appuserlisting_new">App User Listing</a>
        </div>
      </div>

1 Ответ

0 голосов
/ 08 мая 2019

Я думаю, это будет работать.Вы можете использовать BehaviorSubject для связи между различными компонентами приложения.Вы можете определить службу обмена данными, содержащую BehaviorSubject, на которую можно подписаться и отправлять изменения.

Определить службу обмена данными

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';

@Injectable()
export class DataSharingService {
    public isUserLoggedIn: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
}

Добавьте DataSharingService в вашу запись AppModule поставщиков.

Затем импортируйте DataSharingService в <app-header> и в компонент, где вы выполняете операцию входа.В <app-header> подпишитесь на изменения в isUserLoggedIn subject:

import { DataSharingService } from './data-sharing.service';

export class AppHeaderComponent { 
    // Define a variable to use for showing/hiding the Login button
    isUserLoggedIn: boolean;

    constructor(private dataSharingService: DataSharingService) {

        // Subscribe here, this will automatically update 
        // "isUserLoggedIn" whenever a change to the subject is made.
        this.dataSharingService.isUserLoggedIn.subscribe( value => {
            this.isUserLoggedIn = value;
        });
    }
}

В ваш <app-header> html шаблон необходимо добавить условие *ngIf, например:

<button *ngIf="!isUserLoggedIn">Login</button> 
<button *ngIf="isUserLoggedIn">Sign Out</button>

Наконец, вам нужно просто отправить событие, как только пользователь вошел в систему, например:

someMethodThatPerformsUserLogin() {
    // Some code 
    // .....
    // After the user has logged in, emit the behavior subject changes.
    this.dataSharingService.isUserLoggedIn.next(true);
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...