简体   繁体   English

遍历angular2打字稿中的数组

[英]Iterating through an array in angular2 typescript

Am new to typescript and angular2 and learnining this and i have this issue. 我是打字稿和angular2的新手,对此进行了学习,我遇到了这个问题。 I have a form that i would like to show the results of an array of items but these items keep changing everytime so i dont now the actual index of the returned results. 我有一个表格,我想显示一组项目的结果,但是这些项目每次都在变化,所以我现在不返回结果的实际索引。

This is the case 就是这样

I have this form.html 我有这个form.html

<span style="color:red">{{usererror.username}}  </span>
...other items here
<span style="color:red">{{usererror.password}}  </span>

Now in the component 现在在组件中

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


}

}

As from the above function the first log returns an array of the form 从上面的函数开始,第一个日志返回以下形式的数组

[{"field":"username","message":"Username cannot be blank."},
  {"field":"password","message":"Password cannot be blank."}]

Now i would like to assign the username and password variables in the above usererror so that they can be displayed 现在我想在上述usererror中分配用户名和密码变量,以便可以显示它们

So something like this 所以像这样

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

     }
 }

sometimes the returned results dont have a username field and sometimes the password field. 有时返回的结果没有用户名字段,有时没有密码字段。 How do i go about this, am still new to angular2 and typescript 我该如何解决,仍然是angular2和Typescript的新手

Use the square bracket notation ( object["property"] ) : 使用方括号表示法( object["property"] ):

let messages= JSON.parse( error._body);
for (let message of messages){
    if(this.usererror[message.field])
      this.usererror[message.field]=message.message;
}

If all you require is to check whether this.usererror.message[i].field exists, before attempting to copy the message, then you can include an if statement like this: 如果您只需要检查this.usererror.message[i].field是否存在,然后再尝试复制消息,则可以包含以下if语句:

for (var i=0; i<message.length; i++){
    if(this.usererror.message[i].field){
        this.usererror.message[i].field = message[i].message;
    }
}

If the field is undefined , as in it does not exist, then that if statement will return false . 如果该字段是undefined ,因为它不存在,那么if语句将返回false

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM