配置状态服务
ConfigStateService 是一个单例服务,即在应用的根级别提供,并在内部存储中维护应用配置响应。
使用前准备
要使用 ConfigStateService,您必须在类中将其作为依赖项注入。
import { ConfigStateService } from '@abp/ng.core';
import { inject } from '@angular/core';
@Component({
/* 此处为类元数据 */
})
class DemoComponent {
private config = inject(ConfigStateService);
}
您无需在组件或指令级别提供 ConfigStateService,因为它已经在根级别提供。
获取方法
ConfigStateService 拥有多种获取方法,允许您获取特定配置或所有配置。
方法名称以"$"结尾的获取方法(例如 getAll$)返回一个RxJs流。当状态被设置或更新时,这些流会被触发。
如何获取所有配置
您可以使用 ConfigStateService 的 getAll 或 getAll$ 方法来获取整个应用配置响应对象。使用方法如下:
// this.config 是 ConfigStateService 的实例
const config = this.config.getAll();
// 或
this.config.getAll$().subscribe((config) => {
// 在此处使用配置
});
如何获取特定配置
您可以使用 ConfigStateService 的 getOne 或 getOne$ 方法来获取特定的配置属性。为此,应将属性名称作为参数传递给该方法。
// this.config 是 ConfigStateService 的实例
const currentUser = this.config.getOne("currentUser");
// 或
this.config.getOne$("currentUser").subscribe((currentUser) => {
// 在此处使用当前用户信息
});
有时,您可能希望比仅获取当前用户更具体。例如,以下是获取 tenantId 的方法:
const tenantId = this.config.getDeep("currentUser.tenantId");
// 或
this.config.getDeep$("currentUser.tenantId").subscribe((tenantId) => {
// 在此处使用租户ID
});
或者通过传递键名数组作为参数:
const tenantId = this.config.getDeep(["currentUser", "tenantId"]);
供参考,getDeep 能够完成 getOne 的所有功能。只需注意 getOne 速度略快。
如何获取功能
您可以使用 ConfigStateService 的 getFeature 或 getFeature$ 方法来获取功能值。为此,应将功能名称作为参数传递给该方法。
// this.config 是 ConfigStateService 的实例
const enableLdapLogin = this.config.getFeature("Account.EnableLdapLogin");
// 或
this.config
.getFeature$("Account.EnableLdapLogin")
.subscribe((enableLdapLogin) => {
// 在此处使用LDAP登录启用状态
});
更多信息,请参阅功能文档。
如何获取设置
您可以使用 ConfigStateService 的 getSetting 或 getSetting$ 方法来获取设置。为此,应将设置名称作为参数传递给该方法。
// this.config 是 ConfigStateService 的实例
const twoFactorBehaviour = this.config.getSetting(
"Abp.Identity.TwoFactor.Behaviour"
);
// 或
this.config
.getSetting$("Abp.Identity.TwoFactor.Behaviour")
.subscribe((twoFactorBehaviour) => {
// 在此处使用双因素认证行为设置
});
更多信息,请参阅设置文档。
状态属性
有关使用 getOne 和 getDeep 可以获取的所有属性,请参考 ApplicationConfigurationDto 类型。可在 models.ts 文件 中找到。
设置状态
ConfigStateService 有一个名为 setState 的方法,允许您设置状态值。
您可以获取应用配置响应并设置 ConfigStateService 状态值,如下所示:
import { AbpApplicationConfigurationService, ConfigStateService } from '@abp/ng.core';
import { inject } from '@angular/core';
private abpApplicationConfigurationService = inject(AbpApplicationConfigurationService);
private config = inject(ConfigStateService);
constructor() {
this.abpApplicationConfigurationService.get({ includeLocalizationResources: false }).subscribe(config => {
this.config.setState(config);
})
}
抠丁客


