Acquire MySQL data via PHP using Angular HttpClient's POST processing
WARNING: This is a Google translated (originally Chinese) and reposted article that probably is mostly comfortably understandable for senior JavaScript developers.
Since the environment improvement was finished for the time being, we reviewed the application creation, so we can not take 404 in front of it HttpClientModule, we also make a note of the production procedure in zero base as a combination of verification and procedure arrangement.
Outline of processing
A process of acquiring MySQL data via PHP using POST processing of HttpClient and displaying it with the grid of wijmo.
Environment and procedures
The environment is below.
- Angles
- MAMP
- PHP
- MySQL
ng new After creating a new project with the following flow.
- Create test table / data
- PHP creation to retrieve / return table data
- Add wijmo package
- Add wijmo's CSS and edit angular.json
- Edit app.component.ts
- Edit app.component.html
Implementation method
Create test table / data
CREATE TABLE `test` (
`user_no` varchar(20) NOT NULL,
`user_name` varchar(30) DEFAULT NULL,
`user_info` text NULL,
PRIMARY KEY (`user_no`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO
`test` ( ` user_no` , `user_name` , ` user_info` )
VALUES
( '1' , 'user 1' , 'user 1 info' ),
( '2' , 'user 2' , 'user 2 Information ' ),
( ' 3 ' , ' user 3 ' , ' user 3 information ' );
PHP creation to retrieve / return table data
Because I forget how to write variously there are some doubtful parts, but communication is done so it is good.
define('DSN','mysql:host=localhost;dbname=angular_test');
define('DB_USER','root');
define('DB_PASSWORD','root');
error_reporting(E_ALL & ~E_NOTICE);
function connectDb() {
try {
return new PDO(DSN, DB_USER, DB_PASSWORD);
} catch (PDOException $e) {
echo $e->getMessage();
exit;
}
}
mb_language("uni");
mb_internal_encoding("utf-8"); //内部文字コードを変更
mb_http_input("auto");
mb_http_output("utf-8");
$dbh = connectDb();
$sth = $dbh->query("SELECT * FROM test");
$userData = $sth->fetchAll();
//jsonとして出力
header('Content-type: application/json');
echo json_encode($userData, JSON_UNESCAPED_UNICODE);
Add wijmo package
Since DB data is displayed in grid this time
npm install wijmo --save
Package addition by.
Add wijmo's CSS and edit angular.json
Copy wijmo.min.css and specify the path in angular.json. The concrete procedure is to use Wijmo as an Angular library "See style.css for wijmo and reading language files" .
Edit app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { HttpClientModule } from '@angular/common/http';
import { WjGridModule } from 'wijmo/wijmo.angular2.grid';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule
, HttpClientModule
, WjGridModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Edit app.component.ts
import { Component, OnInit } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { timeout, catchError} from 'rxjs/operators';
import { Observable, throwError } from 'rxjs';
const HTTP_OPTIONS = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
};
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
public girdData: any;
/ **
* Constructor
*/
constructor(
private _http: HttpClient) {
let postUrl;
postUrl = 'works/angular_test/test.php';
this.http(postUrl, '').subscribe(
res => {
this.girdData = res;
}
, error => {
console.log(error);
}
, () => {
console.log('complete');
}
);
}
/ **
* Initialization processing (default)
* Without @ param
* No @return
* /
public ngOnInit () {
}
/ **
* http post processing
* @ param {string} _postUrl - Outgoing URL
* @ param {any} _trans_data - transmission data
* @return {Observable} http.post処理
*/
public http(_postUrl: string, _trans_data: any): Observable<any> {
let ret;
ret = this._http.post(_postUrl, _trans_data, HTTP_OPTIONS)
.pipe(
timeout(5000),
catchError(this.handleError())
);
return ret;
}
/ **
* Return error of Observable
* Without @ param
* @return {Observable}
*/
private handleError() {
return (error: any): Observable<any> => {
return throwError(error.message);
};
}
}
Edit app.component.html
Data acquisition test
[headersVisibility]="'Column'">
[header]="'ユーザーNo'"
[binding]="'user_no'"
[width]="100">
[header]="'ユーザー名'"
[binding]="'user_name'"
[width]="200">
[header]="'ユーザー情報'"
[binding]="'user_info'"
[width]="300">
Proxy.conf.json
The default build settings If the URL http://localhost:4200/when you try to post processing to the server URL that php is running become a Access-Control-Allow-Originkilling 404 (Not Found)because occurs in the build settings for access via the proxy. Procedures are proxy.conf.jsoncreated in the project root and contents
{
"/works/angular_test/*": {
"target": "http://localhost:80",
"secure": false
}
}
Described in conformity with the server setting of php. After package.jsonthat
≈ 省略 ≈
"scripts": {
"ng": "ng",
"start": "ng serve --proxy-config proxy.conf.json",
"build": "ng build",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e"
},
≈ 省略 ≈
Completion
npm start
When the screen is displayed, it is ready. It will not be 404 Not Foundwrong as HttpClient's implementation method because it can be taken properly to change the destination URL to one that does not exist . If so, the server is still doubtful ....