Geoff
Geoff

Reputation: 6649

Iterating through an array in angular2 typescript

Am new to typescript and angular2 and learnining this and i have this issue. 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

<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

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

Upvotes: 0

Views: 14091

Answers (2)

Jason Evans
Jason Evans

Reputation: 29186

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:

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.

Upvotes: 1

n00dl3
n00dl3

Reputation: 21584

Use the square bracket notation (object["property"]) :

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

Upvotes: 2

Related Questions