Chen Hanhan
Chen Hanhan

Reputation: 1729

can't receive the parameters sent by http request post in Angular 6

This is my code. I make http post request to posts-experiencias.php file and I am trying to get data by $_REQUEST global variable and I can't receive nothing. Do you know why?

post.service.ts

import { Injectable } from '@angular/core';
import { HttpHeaders, HttpClient } from '@angular/common/http';
import { Post } from './post';

const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type': 'application/json',
  })
};

@Injectable({
  providedIn: 'root'
})
export class PostService {

  private postsUrl = 'http://local.blog.com/controllers/posts-experiencias.php';

  getPostsSegunSeccion(seccion) {
    const obj = {
      nome: 'gabriel',
      age: 20
    };
    return this.http.post(this.postsUrl, JSON.stringify(obj), httpOptions);
  }

}

post.component.ts

import { Component, OnInit } from '@angular/core';
import { PostService } from './post.service';
import { Post } from './post';

@Component({
  selector: 'app-posts',
  templateUrl: './post.component.html',
  styleUrls: ['./post.component.css']
})
export class PostComponent implements OnInit {

  seccion: string;
  constructor(private postService: PostService) {}

  actualizarPosts(event) {
    this.seccion = event.target.attributes['data-categoryvalue'].value;
    this.postService.getPostsSegunSeccion(this.seccion)
      .subscribe((data) => {
        console.log(data)
      });
  }

}

Upvotes: 0

Views: 86

Answers (2)

Chen Hanhan
Chen Hanhan

Reputation: 1729

In my case, as it receives the data in Json format, I had to use file_get_contents ('php: // input') instead of using the $ _REQUEST to receive them.

posts-experiencias.php

// Collect the data that has been sent in Json format (String)
$dataInJsonString = file_get_contents('php://input');

// decode Json 
$decodedData = json_decode($dataInJsonString);

echo $decodedData->age;
echo $decodedData->nome;

Upvotes: 0

SiddAjmera
SiddAjmera

Reputation: 39432

By doing this:

const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type': 'application/json',
  })
};

You've set the Content-Type to application/json. Which means, your server will be expecting a JSON Payload.

But by doing JSON.stringify(obj) in getPostsSegunSeccion, you're essentially sending string and not a JSON Object.

So you'll need to remove JSON.stringify from getPostsSegunSeccion and that should fix the issue for you. Your getPostsSegunSeccion should look something like:

getPostsSegunSeccion(seccion) {
  const obj = {
    nome: 'gabriel',
    age: 20
  };
  return this.http.post(this.postsUrl, obj, httpOptions);
}

Upvotes: 1

Related Questions