Mandip Vora
Mandip Vora

Reputation: 309

Http.post not working when 'application/json' set in header in Angular4 cli

I am beginner in the Angular CLI, I have used the login api:'http://localhost/appointjobs/index.php/admin_api/index' using http.post but, I didn't get the post data in server side(codeigniter/php) when set 'content-type:application/json'. Below code I have used in the login services, and also getting post data when I used 'application/x-www-form-urlencoded' instead of 'application/json'.

DataService.ts file:  

import { BadInputError } from './../common/bad-input-error';
import { error } from 'selenium-webdriver';
import { AppError } from './../common/app-error';
import { Observable } from 'rxjs/Observable';
import { Http, ResponseOptionsArgs,RequestOptionsArgs,Headers,RequestOptions } from '@angular/http';
import { Injectable } from '@angular/core';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import 'rxjs/add/observable/throw';
import { NotFoundError } from '../common/not-found-error';
import { Response } from '@angular/http/src/static_response';
import { HttpHeaders } from '@angular/common/http';



 @Injectable()
 export class DataService {

    constructor(private http:Http) {
 }



   getWhere(url,resource){
     let headers= new Headers();
     //headers.append('Access-Control-Allow-Origin:','*');
     headers.append('Accept','text/plain');
     headers.append('content-type','application/json');
     //headers.append('content-type','application/x-www-form-urlencoded');
     let option= new RequestOptions({headers:headers});

    return this.http.post(url,JSON.stringify(resource),option)
      .map(response=>response.json())
    .catch(this.handleError);
   }
 }

AuthService.ts file:

import { DataService } from './data.service';
import { Injectable } from '@angular/core';



@Injectable()
export class AuthService{

private url = 'http://localhost/appointjobs/index.php/admin_api/index';
constructor(private dataService:DataService) {
}

signIn(params:HTMLInputElement){
  this.dataService.getWhere(this.url,params)
  .subscribe(response=>{
    console.log(response);
  });
 }
}

Upvotes: 4

Views: 2478

Answers (1)

Arun Kumaresh
Arun Kumaresh

Reputation: 6311

Use FormData send your data to php

change your service to below

getWhere(url,resource){

     const formData: FormData = new FormData();
     formData.append('data', JSON.stringify(resource));

     let headers= new Headers();
     headers.append('Accept', 'application/json');

    return this.http.post(url,formData, { headers: headers })
      .map(response=>response.json())
    .catch(this.handleError);
   }
 }

and in your php

print_r($_POST['data']); // gives you the json

use

json_decode($_POST['data']) // converts your json string into object

Upvotes: 2

Related Questions