首页 > 解决方案 > 如何从角度 7 的服务评估 app.component 中的条件?

问题描述

我的 app.component.html 有问题,我正在使用这个块:

<router-outlet *ngIf="!accessGranted"></router-outlet>
<div *ngIf="accessGranted" class="wrapper">
    <app-header></app-header>
    <app-left-menu></app-left-menu>

    <router-outlet></router-outlet>

    <app-footer></app-footer>
    <app-right-menu></app-right-menu>
</div>

当它accessGranted为假时,我加载登录主题,当accessGranted它为真时,我从仪表板加载所有内容。好的,这是完美的,我期待的作品。但问题是......如何accessGranted从服务更新变量?目前我在 app.component.ts 中有这个:

app.component.ts

import { Component, OnInit, OnDestroy } from '@angular/core';
import { ThemeService } from './services/theme.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit, OnDestroy {
  title = 'SmartliveWeb';

  accessGranted: boolean;

  constructor (private _themeService: ThemeService) {
    this.accessGranted = _themeService.accessGranted;
  }
}

主题服务.ts

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

@Injectable({
  providedIn: 'root'
})
export class ThemeService {

  accessGranted = false;

  constructor() {
  }
}

当用户登录应用程序时,我想更改accessGranted为 true 以更改主题,但始终保持为 false。当服务更改时,有什么方法可以在 app.component 中应用accessGranted更改?

标签: angularangular7

解决方案


要更新组件中的值,您需要创建该变量的 Observable,以便在更改变量时触发值并且组件可以侦听它。例如:

  private static accessGranted = new Subject();
  accessGranted$ = ThemeService.accessGranted.asObservable();


onLogin(){
   if(loginSuccess){
      ThemeService.accessGranted.next(true);
   }else{
      ThemeService.accessGranted.next(false);
   }
}

在 app.component 中,您可以按如下方式订阅:

ngOnInit(){
   this._themeService.accessGranted$
          .subscribe((res) => this.accessGranted = res)
}

但我认为这不是正确的做法。您可以将其用作子路由并使用 Angular 提供的路由保护,例如 canActivate。在此处获取更多信息:CanActivate Doc


推荐阅读