0

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

2 Answers 2

2

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;
}
Sign up to request clarification or add additional context in comments.

Comments

1

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.

2 Comments

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
Can you show, in your question, how this.usererror is populated?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.