Monday, 3 April 2017

How do i create a put request to update a local json file using express, nodejs and Angular CLI

I am trying to update a local JSON file with a button click to update the state of the button. Currently i am able to get the JSON file and read all button state. below am pasting my button_status.json file.

[
{
  "id": "0x11",
  "name": "cam1",
  "state": true
},
{
  "id": "0x12",
  "name": "cam2",
  "state": true
},
{
  "id": "0x13",
  "name": "cam3",
  "state": false
},
{
  "id": "0x14",
  "name": "cam4",
  "state": false
},
{
  "id": "0x15",
  "name": "cam5",
  "state": false
},
{
  "id": "0x111",
  "name": "cam6",
  "state": false
}]

i am using express nodejs server for reading the button_status.json file. below am adding my express get function.

app.get('/getButtons', function (req, res) {
fs.readFile( __dirname + "/" + "button_status.json", 'utf8', function (err, data) {
   console.log( data );
   res.end( data );
});
});

Angular service code to call the get method.

getButtonStatus() {
return this.http.get('http://localhost:3000/api/getButtons')
             .map(res => res.json())
             .concatMap(res => res)
             .filter((x:any) => x.state === true)
             .do(res=> console.log("res",res))
}

with the below code i am removing the hidden property for which the button state is true.

this.buttonStatus = _mcxAppLayoutService.getButtonStatus()
.subscribe(value=>{
  $('#'+value.name).removeAttr('hidden');
});

Now i want to change the button state to true/false in the JSON file when anyone want to change using some button click event. how can i create a put request to update the state of each button. can anyone help me to do this. thanks for your help in advance.



via NMNB

No comments:

Post a Comment