You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular13中TypeScript类绑定JSON并保留默认值可行吗?

在Angular 13中实现带默认值的TypeScript类与JSON绑定

直接将JSON对象赋值给类变量无法保留默认值,原因是JSON是普通JavaScript对象,并未触发类的实例化过程,类中定义的默认属性不会自动初始化。以下是几种可行的解决方案:

方案一:通过构造函数合并参数与默认值

修改OidcConfig类,添加构造函数接收JSON参数,利用Object.assign将传入的属性覆盖到类实例上,未传入的属性则保留类定义的默认值:

export class OidcConfig {
    displayName: string;
    issuer: string;
    clientId: string = "app";
    sessionChecksEnabled: boolean = false;

    constructor(config: Partial<OidcConfig>) {
        Object.assign(this, config);
    }
}

使用方式:

const jsonConfig = {
   "displayName": "Keycloak",
   "issuer": "https://sso.example.com/realms/my-realm"
};

// 创建类实例并绑定JSON
const oidcConfig = new OidcConfig(jsonConfig);
// 此时 oidcConfig.clientId === "app",oidcConfig.sessionChecksEnabled === false

方案二:使用工厂函数创建实例

如果不想修改类的构造函数,可以编写一个工厂函数,先创建带默认值的类实例,再将JSON属性合并进去:

export class OidcConfig {
    displayName: string;
    issuer: string;
    clientId: string = "app";
    sessionChecksEnabled: boolean = false;
}

// 工厂函数
export function createOidcConfig(json: Partial<OidcConfig>): OidcConfig {
    const configInstance = new OidcConfig();
    return Object.assign(configInstance, json);
}

使用方式:

const jsonConfig = { /* JSON配置 */ };
const oidcConfig = createOidcConfig(jsonConfig);

方案三:结合HttpClient的响应转换(适用于API获取的JSON)

如果JSON是通过Angular的HttpClient从后端获取的,可以在请求管道中使用map操作符将响应转换为类实例:

import { HttpClient } from '@angular/common/http';
import { map } from 'rxjs/operators';

// 假设在某个服务中
constructor(private http: HttpClient) {}

fetchOidcConfig() {
    return this.http.get<Partial<OidcConfig>>('/api/oidc-config')
        .pipe(
            map(json => new OidcConfig(json))
            // 或使用工厂函数:map(json => createOidcConfig(json))
        );
}

注意事项

不要使用类型断言直接赋值(如const config: OidcConfig = jsonConfig),这种方式仅在编译时做类型检查,运行时仍然是普通JSON对象,不会触发类的默认值初始化。

内容的提问来源于stack exchange,提问作者ciis0

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 00:33:21