Search code examples
mysqlangularangular4-httpclient

POST data in server - angular 4


I have created a small program which is used to post the data and get the result back in the server.I have created a button in .html and function works fine.I am getting access log from the server side once I click POST button. But I couldnot display the data. Should I use GET function again or is there any simple way ?

app.component.ts

 import {Injectable, Component } from '@angular/core';
 import { Http, Response, RequestOptions, Headers} from '@angular/http';
 @Component({
 selector: 'app-root',
 templateUrl:'app.component.html'
 })

 export class AppComponent {
 result;
 constructor (private http:Http) {

 }

 executeHttp() {
 var headers = new Headers();
 //this.createAuthorizationHeader(headers);
 headers.append('Content-Type', 'application/json');
 var content = JSON.stringify({
 name: 'my name'
 });

  return this.http.post(
 'http://100.000.00.000/webservices/voltage-info-service/server/server.php', content, {
  headers: headers
  }).map(res => res.json()).subscribe((data)

  => { '<?xml version="1.0" encoding="utf-8"?><lfc:requests><lfc:request><lfc:busID>66</lfc:busID><lfc:timestamp>223456789</lfc:timestamp><lfc:coordinates>'+
    '<lfc:LongD>8</lfc:LongD><lfc:LongM>6</lfc:LongM><lfc:LongS>25.599</lfc:LongS><lfc:LatD>51</lfc:LatD><lfc:LatM>33</lfc:LatM><lfc:LatS>23.9898</lfc:LatS>'+
    '</lfc:coordinates></lfc:request></lfc:requests>';},

    this.result =data;
    console.log("data");  },
    err => { console.log(err); }
  );
  }
  }

  app.component.html

  <li>
    <button type="submit" (click)="executeHttp()">SOAP request </button>
  </li>

Solution

  • So a better approach would be if you make an attribute on the AppComponent, like 'result'.

     export class AppComponent {
       result;
     ...
    

    Then in the subscribe next section something like:

    .subscribe((data) => {
      this.result = data;
    })
    

    and then in app.component.html:

    <div>{{result}}</div>