如何在 Angular 中为键值对属性设置值?



假设我有给定的对象:

export interface File {
id: string;
displayname: string;
filesize: number;
isarchived: boolean;
userId: string;
[key: string]: any;
}

和以下方法:

export class BasketService {
addFile(file: File ) { //Some code here }
}

比我这样称呼我的方法:

this._basketService.addFile({
id: file.id,
displayname: file.originalEntry['displayname'],
filesize: file.originalEntry['filesize'],
isarchived: file.originalEntry['isarchived'],
userId: this._appSession.user.id,
???: file.originalEntry // <=== How can I set the key value pair here?
});

对象:

file.originalEntry is [key: string].我想传递整个对象 而不是单个键/值对。

尝试如下:

this._basketService.addFile({
id: file.id,
displayname: file.originalEntry['displayname'],
filesize: file.originalEntry['filesize'],
isarchived: file.originalEntry['isarchived'],
userId: this._appSession.user.id,
keyValue: {key:file.id, value: file.originalEntry}
});

如果声明是这样的:

public dictionary: { [key: string]: string } = {};

您可以通过以下方式设置其值:

this.dictionary = { ID: key, Value: defaultValue }; // key and defaultValue are variables

在您的情况下,通过以下内容:

{ ID: key, Value: defaultValue }

我解决了它,在我的对象中明确放置了我需要的键/值对,如下所示:

const digitalObject = {
id: file.id,
displayname: file.originalEntry['displayname'],
filesize: file.originalEntry['filesize'],
isarchived: file.originalEntry['isarchived'],
userId: this._appSession.user.id,
code: file.originalEntry['code'],
needle: file.originalEntry['needle'],
x8: file.originalEntry['x8'][0],
x5: file.originalEntry['x5'][0],
8: file.originalEntry['8'][0],
5: file.originalEntry['5'][0],
creationtime: file.creationTime
};
this._basketService.addFile(digitalObject);

感谢您的所有贡献。

最新更新