Fetching json data from server-side php file with angular? - javascript

I'm using plain javascript to fetch data from php scripts server-side but I'd like to try it out using angular.
This code fetches a php file that in turn queries a database (simple select with filter, etc) and returns a json file to be used by the script and then displayed.
Is there a simple way of doing this with angular?
This is the script as it is now
fetch('service/select.php')
.then(function(response) {
return response.json();
})
.then(function(data) {
//do something with the data
});
and this is the php file it fetches:
<?php
require_once("config.php");
mysqli_set_charset($con, 'utf8mb4');
mysqli_query($con, "SET NAMES 'utf8mb4'");
$rs = mysqli_query($con, "select * from names");
while($row = mysqli_fetch_assoc($rs)) {
$res[] = $row;
}
echo json_encode($res, JSON_UNESCAPED_UNICODE);
?>
(I know the php file is vulnerable to sql injection, its just an example file to quickly query data, not used in production)

Demo HTTPClient module is your need
import {Injectable} from '#angular/core';
import { HttpClient, HttpHeaders } from '#angular/common/http';
import { Observable, throwError } from 'rxjs';
import { retry, catchError } from 'rxjs/operators';
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
};
#Injectable()
export class DataService{
constructor(private http:HttpClient){ }
Post(url:string,body:any): Observable<any>{
return this.http.post<any>(url, body, httpOptions).pipe( retry(1), catchError(this.handleError) );
}
Get(url:string): Observable<any>{
return this.http .get<any>(url, httpOptions).pipe( retry(1), catchError(this.handleError) );
}
private handleError(error: any){
let body = error.json();
return body || {};
}
}

Angular provides HttpClient API to do HTTP requests. The response type of this API is Observable type of RxJS which has lots of built-in methods to
process your data.
You can do your HTTP request code as following in the angular way instead of fetch API.
const url = 'service/select.php';
const hdrs = new HttpHeaders({ 'Accept': accept ? accept : 'application/json; charset=utf-8' });
this.http.get(url, { headers: hdrs, observe: 'body', responseType: 'json'})
.subscribe(
data => // do whatever you want to do your data
err => // get the error response here
);

Related

How can I take the data in this service from an HTTP get call?

I have a little issue from an Angular app to get a code from my own server.
I´ve built up a little Spotify App for learning more about Angular 10 and have a little backend that I only use for get the Bearer code to call the Spotify API, but the fact is that in my Angular front I can´t save the code.
Tis is my service call code to the back:
import { Injectable } from '#angular/core';
import { HttpClient, HttpHeaders } from '#angular/common/http';
import { map } from 'rxjs/operators';
import { environment } from '../../environments/environment';
#Injectable({
providedIn: 'root'
})
export class SpotifyService {
token: any;
constructor(private http: HttpClient) {
console.log('Spotify service ready');
this.getAccesToken().subscribe(data => this.token = data['access_token']);
}
getAccesToken(){
return this.http.get(environment.server + `${environment.client_id}/${environment.client_secret}`)
.pipe(
map(res => res)
);
}
getQuery(query: any){
const headers = new HttpHeaders({
'Authorization': `Bearer ${this.token}`
});
const url = `https://api.spotify.com/v1/${query}`;
return this.http.get(url, {headers});
}
I´ve checked the recibed data and I get the request perfectly, but can´t save the data of the suscriber into a variable.
Thanks in advance!
Assuming your component code looks like below, you can make some adjustments and try it.
export class SomeComponent implements OnInit {
spotifyData;
user;
token;
constructor(private spotifyService: SpotifyService, private http: HttpClient) { }
ngOnInit() {
this.user = JSON.parse(localStorage.getItem('user'));
console.log(this.user);
this.token = this.user.token;
this.getSpotifyData();
}
getSpotifyData() {
this.spotifyService.getQuery(this.user, { headers: new HttpHeaders().set('Authorization', 'Bearer ' + this.token) }).subscribe(res => {
console.log(res);
if (res) {
spotifyData = res;
} else {
spotifyData = []
}
});
}

Angular http module - post headers

I'm unable to change the headers when doing a post request with http module in Angular (with Ionic).
Here is my code:
import { Injectable } from '#angular/core';
import { HttpClient, HttpHeaders } from '#angular/common/http';
const apiUrl = "https://webhook.site/c2d56330-84d4-47cf-9f98-472f7eac8000";
#Injectable({
providedIn: 'root'
})
export class APIService {
constructor(private http: HttpClient) { }
getToken(){
var body = {
'data1': 'data2',
'somedata3': 'data4',
};
let headers = new HttpHeaders().append('Content-Type', 'application/json');
this.http.post(apiUrl, JSON.stringify(body), {headers}).subscribe(data =>
console.log(data));
console.log(headers.get('Content-Type')); //return 'application/json'
}
}
Everything works well, but it still sends header "content-type: text/plain" instead of "content-type: application/json".
Do I type something wrong?
I'd prefer something like:
import { HttpHeaders } from '#angular/common/http';
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
};
this.http.post<Foo>(this.apiUrl, body, httpOptions)
Also I don't see a need to stringify the body, just pass it as a "normal" object

Need to click twice to update server - Angular2

I have a json that is not being update on the first time I click on the button that updates it. The button in question calls this function:
recusaProposta(){
this.propostaService.atualizaDisputa(this.disputa)
.subscribe(
res => this.disputa.propostas_realizadas++,
error => console.log(error)
);
}
Now, at the first time I click on it nothing happens on the json but if I click on it again it does update the field I want (disputa.propostas_realizadas)
Here's the service:
import {Injectable} from '#angular/core';
import {Http, Headers, Response, RequestOptions} from '#angular/http';
import {Component} from '#angular/core';
import {Observable} from 'rxjs/Rx';
import {DisputaPropostaComponent} from './disputas-proposta.component';
import 'rxjs/add/operator/map';
#Injectable()
export class DisputaPropostaService{
contato:Object[] = [];
name: string;
headers:Headers;
url: string = 'http://localhost:3004/disputa';
constructor(private http: Http){}
atualizaDisputa (body:any): Observable<DisputaPropostaComponent[]>{
let bodyString = JSON.stringify(body); // Stringify payload
let headers = new Headers({ 'Content-Type': 'application/json' }); // ... Set content type to JSON
let options = new RequestOptions({ headers: headers }); // Create a request option
return this.http.put(`${this.url}/${body['id']}`, body, options) // ...using post request
.map((res:Response) => res.json()) // ...and calling .json() on the response to return data
.catch((error:any) => Observable.throw(error.json().error || 'Ocorreu um erro em nosso servidor, tente novamente mais tarde')); //...errors if any
}
}
Can you guys help me? Thanks in advance.
The reason is that in your function you return disputa.propostas_realizadas before increasing it by 1. Replace your function with the code below and it should work.
recusaProposta(){
this.propostaService.atualizaDisputa(this.disputa)
.subscribe(
res => ++this.disputa.propostas_realizadas,
error => console.log(error)
);
}

Custom Http headers in Angular 2 for every request

In my Angular 2 application, I'm trying to use Http (#angular/http) to make requests to my API. For these requests to work, I need certain headers to be added to every request I make to the API (including a JWT header).
What I'd like to do is have an API class that takes care of creating the Http requests and some error handling and validation etc.
As it turns out, however, I cannot use the Http class from my API class, as it will come up with the following error;
user.service.ts
import { Injectable } from '#angular/core';
import {User} from "../models/User";
import {API} from "../API";
import {Http} from "#angular/http";
#Injectable()
export class UserService
{
constructor (private http : Http) {}
getProfile (user : User)
{
let api = new API (this.http);
return api.doRequest ('/user/' + user.id + '/profile');
}
}
API.ts
import {Http, Headers, RequestOptions} from '#angular/http';
export class API
{
...
constructor (private http : Http) {}
doRequest (url : string, method : string, data?)
{
let headers = {...};
let options = new RequestOptions ({ headers: new Headers (headers), ... } );
return this.http.get (url, data, options)
.catch ((error) => { ... } );
}
}
Things work better when using Http straight from the UserService, however.
Is there a way to fix this, or perhaps a better way to achieve the desired result? Should I just extend Http?
You should be using append() method to add headers and then pass it to request object as below
doRequest (url : string, method : string, data?)
{
headers= new Headers();
headers.append(name1,value1);
headers.append(name2,value2);
....
let options = new RequestOptions ({ headers: headers, ... } );
return this.http.get (url, data, options)
.catch ((error) => { ... } );
}
That's the way today setting HTTP headers (Angular > 4):
Import:
import {HttpClient, HttpHeaders} from '#angular/common/http';
and usage:
const headers = new HttpHeaders()
.set("X-CustomHeader", "custom header value");
Notice that we are building the headers object by chaining successive set() methods. This is because HttpHeaders is immutable, and its API methods do not cause object mutation.
Instead, a call to set will return a new HttpHeaders object containing the new value properties. So this means that the following will NOT work:
const headers = new HttpHeaders ();
headers.set("X-CustomHeader", "custom header value")

Angular2 post request not sending proper data to server

I am taking the field of a form and passing it to a service as this.form.value when I am logging this.form.value on the console I am getting Object { email: "zxzx", password: "zxzxx" } when I am sending the same thing to the service and calling the server like :
import {Http} from 'angular2/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
import {Injectable} from 'angular2/core'
import {Post} from './post';
import {Observable} from 'rxjs/Observable';
#Injectable()
export class PostService {
//dependency injection
private _url = "http://127.0.0.1/accounts/login_user/";
constructor(private _http:Http) {
}
createPost(post){
return this._http.post(this._url,JSON.stringify(post))
.map(res=>res.json());
}
}
The server is being called but the values are not being passed. When I am logging the response on the console I am getting :
Object { _isScalar: false, source: Object, operator: Object }
Can somebody please help me solve this issue?
Thank you.
Your console.log prints the observable corresponding to your request but not its result. If you want to print this result, you can use the do operator:
createPost(post){
return this._http.post(this._url,JSON.stringify(post))
.map(res=>res.json())
.do(data => {
console.log(data);
});
}
You said that the request is executed. It's actually the case if you subscribe on the observable:
this.service.createPost(...).subscribe(() => {
(...)
});
Edit
You also need to set the Content-Type header:
createPost(post){
var headers = new Headers();
headers.append('Content-Type', 'application/json');
return this._http.post(this._url,JSON.stringify(post), { headers })
.map(res=>res.json())
.do(data => {
console.log(data);
});
}
Edit2
If you want to send an url-encoded form:
You also need to set the Content-Type header:
createPost(post){
var headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
let content = new URLSearchParams();
content.set('prop', post.prop);
(...)
return this._http.post(this._url, content.toString(), { headers })
.map(res=>res.json())
.do(data => {
console.log(data);
});
}
You need to subscribe() otherwise the observable won't do anything:
createPost(post){
return this._http.post(this._url,JSON.stringify(post))
.map(res=>res.json())
.do(val => console.log(val));
}
...
this.createPost(...).subscribe(data => console.log(data));

Categories