我是 typescript 和 Angular2 的新手,正在学习这个,我遇到了这个问题。我有一个表单,我想显示一组项目的结果,但这些项目每次都在变化,所以我现在不知道返回结果的实际索引。
是这样的
我有这个form.html
<span style="color:red">{{usererror.username}} </span>
...other items here
<span style="color:red">{{usererror.password}} </span>
现在在组件中
export class LoginComponent implements OnInit{
public usererror={
username:"",
password:""
}
//this function is called after a post request
onLoginError(error:any){
let message= JSON.parse( error._body);
console.log(error._body); //first log
console.log(message) //second log
}
}
从上面的函数中,第一个日志返回以下形式的数组
[{"field":"username","message":"Username cannot be blank."},
{"field":"password","message":"Password cannot be blank."}]
现在我想在上面的用户错误中分配用户名和密码变量,以便可以显示它们
所以像这样
onLoginError(error:any){
let message= JSON.parse( error._body);
let message= JSON.parse( error._body);
for (var i=0; i<message.length; i++){
this.usererror.message[i].field = message[i].message; //this fails since the
//usererror doesnt have (message[i].field) property
}
}
有时返回的结果没有用户名字段,有时没有密码字段。我该如何解决这个问题,我对 Angular2 和 TypeScript 还是新手
最佳答案
使用方括号表示法(object["property"]
):
let messages= JSON.parse( error._body);
for (let message of messages){
if(this.usererror[message.field])
this.usererror[message.field]=message.message;
}
关于javascript - 在 Angular2 typescript 中迭代数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41503340/