I need to know how to pass parameters between angular 7 and a PHP API
import { Injectable } from '#angular/core';
import { HttpClient, HttpParams } from '#angular/common/http';
#Injectable({
providedIn: 'root'
})
export class DataService {
constructor(private http: HttpClient) { }
getUsers() {
return this.http.get('http://localhost/backend/json/data_products.php');
}
getProduct(productId) {
const params = new HttpParams().set('id', productId);
return this.http.get('http://localhost/backend/json/data_product.php/', {params});
}
}
but I got this error
core.js:12584 ERROR HttpErrorResponse {headers: HttpHeaders, status: 200, statusText: "OK
Please refer to Angular doc: https://angular.io/api/common/http/HttpClient#get
get(url: string, options: { headers?: HttpHeaders | { [header:
string]: string | string[]; }; observe?: "body"; params?: Ht...)
It should be like:
this.http.get('http://localhost/backend/json/data_product.php/', { params: params });
in your case.
I think you need to pass header in request like below.May be this is help you.
update(id: number, data: any){
let model = JSON.stringify(data);
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this._http.put( 'http://localhost/backend/json/data_product.php/'+id,model, options);
}
Related
I already developed ionic 4 in my Mac. When trying to improve an app in ionic 3, my http.post (angular) calls in php is received as GET ($ _SERVER ['REQUEST_METHOD']). I discovered that my parameters are not being recognized in php.
* I read the other posts and none solved my problem
Thank you!
import { Http , Headers, RequestOptions} from '#angular/http';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/toPromise';
let parametros = JSON.stringify({
idtApostador: localStorage.getItem("idtApostador"),
});
let headers = new Headers(
{
'Content-Type' : 'application/json'
});
let options = new RequestOptions({ headers: headers });
return new Promise(resolve => {
this.http.post(url, parametros, options)
.timeout(15000)
.subscribe(data => {
})
})
I ask, I answer. :)
https instead of http.
Use
import { HttpClient } from '#angular/common/http';
Instead of HTTP
I have an "api rest" that I created in PHP, the service returns a JSON with the parameters of "header", "body", "get", "pos", which comes to receive without any type of validation.
Now I have created a service in angular to connect with the "api rest", all right up there, the problem I have is that I want to send a parameter as a "BODY", but I do not know how, I have been investigating but I have not found a shape.
Is it possible to send the "body" via HttpClient.get()?
import { Injectable } from '#angular/core';
import { HttpClient, HttpHeaders, HttpParams } from '#angular/common/http';
import { map } from 'rxjs/operators';
import { Observable } from 'rxjs';
#Injectable({
providedIn: 'root'
})
export class ServicioService {
constructor(private http: HttpClient) { }
getQuery(query: string){
const url = `http://localhost:8080/servicio/`;
const headers = new HttpHeaders({
'Authorization': 'Bearer BQAiaibx-we0RSlZFN29B5TPF4t6egxbuuEsc5ZYZhpamHUhImd5'
});
const params = new HttpParams()
.set('page', '2')
.append('page', '3')
.set('sort', 'abc');
return this.http.get (url, { params, headers});
}
getNewReleases(){
return this.getQuery("")
.pipe( map((data: any) => {
return data;
}));
}
}
A GET request does not have a body.
You should use POST or PUT.
You can read here a little bit about the http methods.
About the GET: The GET method requests a representation of the specified resource. Requests using GET should only retrieve data and should have no other effect
So, it would be wrong to send a body because a GET method should not change anything.
I am new to ionic 3 and I can retrieve data in response _body as string format but i can't able to bind key and values.
Here list.ts file
import { Component } from '#angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { SplashScreen } from '#ionic-native/splash-screen';
import { StatusBar } from '#ionic-native/status-bar';
import { Injectable } from "#angular/core";
import { Http } from '#angular/http';
import { HttpClientModule } from '#angular/common/http';
import 'rxjs/add/operator/map';
import { HomePage } from '../home/home';
/**
* Generated class for the ListCustomerPage page.
*
* See https://ionicframework.com/docs/components/#navigation for more info on
* Ionic pages and navigation.
*/
#IonicPage()
#Component({
selector: 'page-list-customer',
templateUrl: 'list-customer.html',
})
export class ListCustomerPage {
data:any = {};
items:any = {};
public res_data: any ='';
constructor(public navCtrl: NavController, public navParams: NavParams, public http: Http) {
this.http = http;
this.res_data= this.navParams.get('res_data');
}
ionViewDidLoad() {
var link='http://localhost/CustomerRegistration/src/php/list.php?id='+this.res_data;
this.http.get(link).subscribe(
data =>{
this.items=data._body;
});
}
}
In console output:
Response {_body: "[{"customer_id":"440","customer_name":"test","cust…ated_at":"2018-08-17 07:55:07","deleted_at":"0"}]", status: 200, ok: true, statusText: "OK", headers: Headers, …}
In list.html page
i get error key value "customer_name" undefine.
<h3>customer name</h3><b>{{items.customer_name }}</b>
how to use response data in list.html
As per response data is in JSON format you need to parse JSON data like below.
this.items = JSON.parse(data);
or in your case, your data is in one step inner with key-value "body".
So use like this :
let jsonResponse = JSON.parse(data);
this.items = data("_body");
this will help you to get data in an array format.
Angular 4.4.4
This is my app component
constructor(
private http: HttpClient,
)
this.http.post('/api.php', {name, age}).subscribe(data => {
console.log(data);
});
api.php -> exit(json_encode($_POST));
Don't receive any data in $_POST
return [];
(let xmlRequest = new XMLHttpRequest();
....
works fine)
I try set header
let headers = new HttpHeaders().set('Content-Type', 'application/json; charset=UTF-8');
not work
Sorry for this question but I spent 1 day and still could not find solution.
ps. client and server has same origin.
You need to put your parameters into a FormData Object on the Angular side.
const params = new FormData();
params.append('para1', 'value1');
params.append('para2', 'value1');
this.http.post('/api.php', params).subscribe(....)
Now you can get the parameters on the PHP part of your project with $_POST['para1'] and $_POST['para2'].
I like this solution more than getting all the stuff with file_get_contents, as it looks more straight forward for me.
please try I hope it will help you
import { Injectable } from '#angular/core';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/map';
import { HttpClient } from '#angular/common/http';
#Injectable()
export class LandingService {
private apiUrl = 'http://localhost:5000/';
list:any;
headers : any;
constructor(private _http: HttpClient){
this.headers = new Headers();
this.headers.append('Content-Type', 'application/json');
}
getsearchResponse(searchText){
this.list ={"sentences":searchText}
return this._http.post(this.apiUrl+'searchBotsNew',this.list,this.headers)
.map(res =>res.json())
.do(data => console.log(JSON.stringify(data)));
}
}
I found the solution to this.
In PHP, $_POST only accept formdata.
With request header 'Content-Type: application/json' you can receive it with file_get_contents('php://input');
So
$_POST = json_decode(file_get_contents('php://input'));
Can you tell me where I'm wrong? When I use the Postman then it's working.But why I cannot do the same using Angular2? Here the backend api is from PHP.I have never used PHP backend before.Is that different than normal ASP.net Web Api? I mean the way we have to send the parameters and all...
Service.ts
import { Injectable } from '#angular/core';
import { Http, RequestOptions, Headers, Response } from '#angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
#Injectable()
export class AuthenticationData {
authenticationEndPoint: string = "https://www.myk.com/admin/index.php?route=api/login";
constructor(public http: Http) {
}
//to login
loginUser(username: string, password: string): Observable<any> {
let headers = new Headers();
headers.append('content-type', 'application/json');
/*let body = {
username: username,
password: password,
}*/ Not working this too :(
let body='username=myname&password=admin';//I tried hardcode value.But not working
let options = new RequestOptions({ headers: headers });
return this.http.post(this.authenticationEndPoint, body, options)
.map(this.extractData)
.catch(this.handleError);
}
private extractData(res: Response) {
let body = res.json();
return body || {};
}
private handleError(error: Response | any) {
let errMsg: string;
if (error instanceof Response) {
const body = error.json() || '';
const err = body.error || JSON.stringify(body);
errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
} else {
errMsg = error.message ? error.message : error.toString();
}
console.error(errMsg);
return Observable.throw(errMsg);
}
}
login.ts
//to login
loginUser(): void {
if (this.loginForm.valid) {
this.authenticationData.loginUser(this.loginForm.value.username, this.loginForm.value.password).subscribe(
data => {
this.response = data;
},
err => {
console.log(err);
},
() => console.log('Complete')
);
}
}
Error:
body: "{"error":"Invalid Request type","status":"201"}", status: 200,
ok: true, statusText: "OK",
Php:
<?php
class ControllerApiLogin extends Controller {
private $error = array();
public function index() {
$json = array();
if (($this->request->server['REQUEST_METHOD'] == 'POST') && !empty($this->request->get['username']) && !empty($this->request->get['password'])) {
if(!empty($this->request->get['username']) && !empty($this->request->get['password'])){
$this->load->language('common/login');
$this->document->setTitle($this->language->get('heading_title'));
// User
$this->registry->set('user', new Cart\User($this->registry));
if ($this->validate()) {
$token = token(32);
$token_count = $this->user->getUniqueToken($token);
if($token_count==0)
{
$this->session->data['token'] = $token;
}else{
$token = token(32);
$token_count = $this->user->getUniqueToken($token);
$this->session->data['token'] = $token;
}
$this->load->model('user/user');
$user_info = $this->model_user_user->getUserByEmail($this->request->get['username']);
$tokeninfo = array();
if(count($user_info) > 0){
$tokeninfo = array(
'token' => $token,
'user_id' => $user_info['user_id'],
'ip' => $this->request->server['REMOTE_ADDR']
);
$date_expired = $this->model_user_user->addUserapitoken($tokeninfo);
}else{
$date_expired = '';
}
$json['token'] = $token;
$json['date_expired'] = $date_expired;
$json['status'] = '200';
}else{
$json['error'] = "No match for Username and/or Password.";
$json['status'] = '201';
}
}else{
$json['error'] = 'Something Went Wrong!!! <br> PLease Enter Correct Login Credentials!!!';
$json['status'] = '201';
}
//$this->response->addHeader('Content-Type: application/json');
//$this->response->setOutput(json_encode($json));
}
else{
$json['error'] = 'Invalid Request type';
$json['status'] = '201';
}
if (isset($this->request->server['HTTP_ORIGIN'])) {
$this->response->addHeader('Access-Control-Allow-Origin: ' . $this->request->server['HTTP_ORIGIN']);
$this->response->addHeader('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
$this->response->addHeader('Access-Control-Max-Age: 1000');
$this->response->addHeader('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
}
$this->response->addHeader('Content-Type: application/json');
$this->response->addHeader('HTTP/1.1'.$json['status']);
$this->response->setOutput(json_encode($json));
}
protected function validate() {
//$this->registry->set('user', new Cart\User($this->registry));
if (!isset($this->request->get['username']) || !isset($this->request->get['password']) || !$this->user->login($this->request->get['username'], html_entity_decode($this->request->get['password'], ENT_QUOTES, 'UTF-8'))) {
$this->error['warning'] = $this->language->get('error_login');
}
return !$this->error;
}
}
OP's feedback: I have to use it like this.Cheers :)
authenticationEndPoint: string = "https://www.myk.com/admin/index.php?route=api/login&username=";
loginUser(username: string, password: string): Observable<any> {
let headers = new Headers();
headers.append('content-type', 'application/json');
let body = '';
let options = new RequestOptions({ headers: headers });
let url = this.authenticationEndPoint + encodeURI(username) + '&password=' + encodeURI(password);
return this.http.post(url, body, options)
.map(this.extractData)
.catch(this.handleError);
}
Original Answer:
headers.append('content-type', 'application/json');
let body='username=myname&password=admin';//I tried hardcode value.But not working
You seem to be setting content type as json. So your body needs to be set as an object. Do:
let body ={
username:myname,
password:admin
}
And then send the request. It should convert this to json and send.
return this.http.post(this.authenticationEndPoint, body, options)
.map(this.extractData)
.catch(this.handleError);
Seems like you want to use URLSearchParams instead, and send the data as x-www-form-urlencoded instead of JSON. The URLSearchParams will encode the parameters as you have tried when hardcoding, but I think your problem is when you are trying to send it as JSON, send it as x-www-form-urlencoded instead. So try this:
import { URLSearchParams } from '#angular/http';
loginUser(username: string, password: string): Observable<any> {
let headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
let body = new URLSearchParams();
body.set('username',username);
body.set('password',password)
let options = new RequestOptions({ headers: headers });
return this.http.post(this.authenticationEndPoint, body.toString(), options)
.map(this.extractData)
.catch(this.handleError);
}
//you need to import this
import { Http, Headers, URLSearchParams, Request, RequestOptions, RequestMethod } from '#angular/http';
this.body= {
"username":myname,
"password":admin
} //body is defined here
let headers = new Headers();
headers.append('HeaderKey', headerValue);
let options = new RequestOptions({
method: RequestMethod.Post,
url: this.authenticationData.loginUser(this.loginForm.value.username, this.loginForm.value.password),
body: this.body,
headers: headers
});
//here you are making request
this.http.request(new Request(options))
.map(res => res.json())
.subscribe(data => {
//data is fetched
if(data.code==200){
this.response = data;
}
else{
console.log("some issue with the api response")}
}, err => {
console.log("ERROR!: ", err);
});
May be this way things will work for you