angular - 如何从角度 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
更改?
解决方案
要更新组件中的值,您需要创建该变量的 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
推荐阅读
- java - 如何从 MySQL 中检索休眠中的多个图像?
- ruby-on-rails - 使用 Google OAuth 2 API 刷新令牌时如何修复“帐户已被删除”
- javascript - javascript中的平滑键盘输入
- reactjs - Nextjs 动态路由排除
- php - 在 WordPress 模板中,如何检测当前页面是 WooCommerce 购物车还是结帐页面?
- python - 使用 numpy 和 numba 提高 groupby-transform 操作的性能
- android - 如何从 Firebase 中检索数据并在 recyclerView 中一一显示孩子
- powershell - 每个文件压缩文件,同名
- flutter - Cloud Firestore 连接我的 Flutter Windows 应用
- swift - 停止 SKAudioNode 播放