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

share

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;
}
share

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.

share
    
Its true it always returns undefined ive checked on the console.log(this.usererror.message[i].field) and its empty and yet the messages array has values and the field names are similar to the usererror model, what could be causing this – GEOFFREY MWANGI Jan 6 at 11:10
    
Can you show, in your question, how this.usererror is populated? – Jason Evans Jan 6 at 11:15

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.