1

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)

2

2 Answers 2

2

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 || {};
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

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
);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.