我的一种方法遇到了奇怪的行为。它打印entity to user
和start loop
,但此后没有任何反应。它卡住了,没有任何错误!它从未到达end loop
,当然也没有到达finished
我真的不知道这是怎么回事。我正在使用类似的方法将一种类型转换为另一种类型,但是我在这里遗漏了一些东西。
方法:
entityToClientUser(users: any) {
const clientUsers = [];
console.log('entity to user');
console.log(users);
for (const u of users) {
console.log('start loop');
clientUsers.push(
new ClientUser(
u.id,
u.username,
u.email,
'',
'',
u.description,
false,
u.registrationDate,
new Date(),
u.role.role ? u.role.role : 1
)
);
console.log('end loop');
}
console.log('finished');
console.log(clientUsers);
return clientUsers;
}
给该方法的对象:
[ {
id: 1,
username: 'test',
email: 'info@example.com',
password: 'b234234c34899hwerwer4535rfa10a666edgfh43',
avatar: null,
ip: null,
description: 'A simple user.',
isGuest: null,
lastAuth: null,
registrationDate: 2019-10-31T23:56:14.170Z
}
]
ClientUser类
export class ClientUser {
id: number;
username: string;
email: string;
avatar: string;
ip: string;
description: string;
isGuest: boolean;
lastAuth: Date;
role: number;
registrationDate: Date;
constructor(id: number, username: string, email: string, avatar: string, ip: string, description: string, isGuest: boolean, registrationDate: Date, lastAuth: Date, role: number) {
this.id = id;
this.username = username;
this.email = email;
this.avatar = avatar;
this.ip = ip;
this.description = description;
this.isGuest = isGuest;
this.registrationDate = registrationDate;
this.lastAuth = lastAuth;
this.role = role;
}
}
答案 0 :(得分:0)
这是因为您将用户定义为以下任何一个:users: any
Typescript不会警告您在这些用户对象之一上引用的任何内容。
您需要将其更改为users: ClientUser[]
或Typescript可以评估的其他形状。
在您的情况下,我建议您这样做:
ClientUserBase.ts
export class ClientUserBase {
id: number;
username: string;
email: string;
description: string;
registrationDate: Date;
role: number;
}
ClientUser.ts
//Inherits common properties from ClientUserBase
export class ClientUser extends ClientUserBase {
avatar: string;
ip: string;
isGuest: boolean;
lastAuth: Date;
constructor(clientUserBase: ClientUserBase, avatar: string, ip: string, isGuest: boolean, lastAuth: Date) {
this.id = clientUserBase.id;
this.username = clientUserBase.username;
this.email = clientUserBase.email;
this.avatar = avatar;
this.ip = ip;
this.description = clientUserBase.description;
this.isGuest = isGuest;
this.registrationDate = clientUserBase.registrationDate;
this.lastAuth = lastAuth;
this.role = clientUserBase.role;
}
要执行的方法:
entityToClientUser(users: ClientUserBase[]) {
const clientUsers: ClientUser[] = [];
console.log('entity to user');
console.log(users);
for (const u of users) {
console.log('start loop');
clientUsers.push(new ClientUser(u, '', '', false, new Date()));
console.log('end loop');
}
console.log('finished');
console.log(clientUsers);
return clientUsers;
}
反正这样...