Passing multiple values in JSON.stringfy in angular6

6.4k Views Asked by At

I tried to pass multiple values to API using JSON.stringfy(). I don't know why my second value is not passing.

This is the code of my attempt:

getUserDetails(email, password){
this.api="http://192.168.1.14/task/public/api/login";
this.http.post(this.api,JSON.stringify(email,password))
.subscribe(data =>
  {
    if(data !=null)
    {
      console.log("LoggedIn Sucess");
    }
    else{
      console.log("Login Failed");
    }
  })
}
3

There are 3 best solutions below

0
On BEST ANSWER

The JSON.stringify() method converts a JavaScript object or value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.

JSON.stringify as name suggests convert a JavaScript object into a string representation.

so try this:

getUserDetails(email, password){
this.api="http://192.168.1.14/task/public/api/login";
this.http.post(this.api,JSON.stringify({email: email, password: password}))
    .subscribe(data => {
        if(data != null) {
            console.log("loggedIn success");
        } else {
            console.log("loggedIn failed");
        }
    })
}
0
On

JSON.stringify as name suggests convert a JavaScript object into a string representation. Most likely to exchange date to/from a web server.

This function expects only one required parameter, that is the object you want to stringify. The reason you were getting the email value but not password was that javascript was ignoring the second parameter.

Having said that, you can either pass your values into an array object, in this format

JSON.stringify([email,password])

In this case your variables shall be stringified into an array of two string values, for example ["[email protected]","somestring"]

Another approach can be to stringify an object, for example

JSON.stringify({email, password})

In this case your variables shall be stringified into a javascript object like this {"email":"[email protected]", "password":"somestring"}

You can also construct your own JSON object like this

JSON.stringify({emailaddress:email, passwordValue: password})

The benefit of constructing a JavaScript object is that on the server side you can receive parameters with names.

Thanks.

0
On

That is normal, that would work only with one value, in fact now you are receiving only "email".

The right syntax for two inputs or more is

this.http.post(this.api,JSON.stringify([email,password]))

and you will receive [email,password]