Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angularjs 4: how to post raw JSON data

I want to send the following request to my php api:

POST /MyProject/api-get?call=get-account HTTP/1.1
Host: localhost

{
"id":1
}

and here is the api:

public function actionApiGet($call){
    $data = json_decode(file_get_contents('php://input'), true);
    ...
}

mycomponent.ts:

import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { ActivatedRoute } from '@angular/router';
import { Api } from '../../services/Api';
import { Account } from '../../models/Account';
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';

@Component({
  selector: 'app-account-individual',
  templateUrl: './account-individual.component.html',
  styleUrls: ['./account-individual.component.css']
})
export class AccountIndividualComponent{

  constructor(private route: ActivatedRoute, private proxy: Api) {
    const myheader = new HttpHeaders().set('Content-Type', 'application/json; charset=UTF-8');

    this.proxy.post2('http://localhost/MyProject/api-get?call=get-account', {"id":1}, {headers: myheader}).subscribe(
      res => {
        if (res["statusCode"] === 1) {
          console.log(res);
        }
      }
    );
  }
}

Api.ts:

import { Injectable } from '@angular/core';
import { Http, Headers, Response, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
import * as Globals from 'Globals';

@Injectable()
export class Api {

    constructor(private http: Http) { }

    postData(url,body){
        return this.http.post(url, body).map(this.extractData).catch(this.handleErrorPromise);
    }

    private extractData(res: Response) {
        let body = res.json();
        return body||{};
    }

    private handleErrorObservable(error: Response | any) {
        console.error(error.message || error);
        return Observable.throw(error.message || error);
    }

    private handleErrorPromise(error: Response | any) {
        console.error(error.message || error);
        return Promise.reject(error.message || error);
    }
}

but unfortunately I got this error:

supplied parameters do not match any signature of call target

like image 298
Mohammad Avatar asked Jan 27 '26 15:01

Mohammad


1 Answers

Use HttpClient instead Http

import { HttpClient } from '@angular/common/http';

constructor(private http: HttpClient){}    

post(url: string, data?: any) {
   return this.http.post(url, data);
}
like image 128
Lucas Fonseca Avatar answered Jan 29 '26 04:01

Lucas Fonseca