如何通过Angular中的字符串文字访问对象

问题描述 投票:0回答:2

我想向用户显示我从“数据”变量中得到的信息

我在网上收到警告,说“不允许通过字符串文字访问对象(无字符串文字)”

this.crud = data['msg'];

我的班级:

export class CrudClass {
    public id?: string;
    public  name: string;
    public email: string;
    public password: string;
}

我的组件:

export class ListComponent implements OnInit {
    private crud: CrudClass[];

    constructor(private router: Router, private apiRoutes: ApiRoutesService) { }

    ngOnInit() {
        this.readApp();
    }

    readApp() {
        this.apiRoutes.readApp().subscribe(
            data => {
                console.log(data);
                this.crud = data['msg'];
            },
            error => {
                console.log(error);
            }
        );
    }
}
angular typescript tslint
2个回答
1
投票

您可以通过多种方式完成

首先禁用规则

/* tslint:disable:no-string-literal */
 this.crud = data['msg'];
/* tslint:enable:no-string-literal */

第二个使用变量而不是字符串文字

更改

this.crud = data['msg'];

to

let key='msg';
this.crud = data[key];

或要在全局范围内禁用它,请在no-string-literal: false中设置tslint.config.json

Related SO post


0
投票

您可以尝试将let对象设置为一个值并将其设置为data属性

像让dataKey ='msg';this.crud = data [dataKey]

© www.soinside.com 2019 - 2024. All rights reserved.