Tuesday 18 July 2017

Angular 4 PHP + MySQL Shared Hosting

                               


                                 How to use Angular and Php on a shared server.


Start

We will look at a simple example of how to apply with Angular and pure Php on a shared server just for ideas.You can check the DEMO for the latest version .


Used technologies


  • Php 5.x
  • MySQL
  • Angular 4 (cli)

Step 1:

First, create a database called "cities" with mysql and a table called "city" in it and add the data for the test.


Res 1.1 (a) Mysql data structure (b) Table


Step 2:

Now let's write a php script that connects to the database and pulls the data.

veritabani.php 

<?php
header("Content-Type: application/json; charset=utf-8");

$conn = new mysqli("localhost", "root", "", "city");
$conn->set_charset("UTF8");
?>
  • We can declare a Content-Type json and return to the client a json.
  • Set the rest according to yourself. When assigning to the host, you will have to enter the host settings.
Let's create cities.php file and include the above database file. 

<?php
require_once  'veritabani.php'; //$conn

$result = $conn->query("SELECT * FROM cities");

$outp = "";
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
    if ($outp != "") {$outp .= ",";}
    $outp .= '{"ID":"'  . $rs["ID"] . '",';
    $outp .= '"name":"'   . $rs["name"]        . '",';
    $outp .= '"country":"'. $rs["country"]     . '"}'; 
}
$outp ='{"records":['.$outp.']}';
$conn->close();
echo($outp);
?>
  • We convert the data from the cities table above into a Json structure and press "echo".
  • If we go to http: //localhost/php-angular-backend/model/cities.php we will see json data like this :
  • So we finished the server by writing simple end-point.

{"records":[{"ID":"1","name":"İstanbul","country":"Turkey"},{"ID":"2","name":"Ankara","country":"Turkey"}]}

Step 3:

Now we go to the client side. Create an infrastructure using angular cli.

  • If Node.js and angular-cli are not installed, you can install NodeJs and angular-cli respectively .
  • We will take advantage of the blessings of these technologies, and we will simply drop the last code on the host.
Once you have done the installations, open any command interpreter (CMD, Terminal, etc.) and enter the following commands in order to create an angular project. 
Note: Run CMD as an administrator on Windows. 

ng new php-angular
cd php-angular
ng serve
Open the project in the code editor. Direct code in project directory in console if you are using Visual Studio Code You can write. 
Write the following code as a console to create our first service to talk to the php server.
ng g service cities

Step 4:

Let's add our service codes.


import { Observable } from 'rxjs/Rx';

import { City } from './city';
// Import RxJs required methods
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/Rx';

@Injectable()
export class CitiesService {
 
  private url = "http://localhost/php-angular-backend/model/cities.php";
  
  constructor(private _http:Http) { }

  getCities(): Observable<City[]>{
      // url:api/users
      // get all Users
       return this._http.get(this.url)
                .delay(2000) //end-point sahte bir gecikme verelim
                .do(console.log) //gerekli değil ama..
                .map((res:Response)=>res.json().records)
                .do(console.log);
   }
}
  • We specify the URL to return json data. (Server address when assigning to server)
  • We inject (inject) the Http service to send the Get request.
  • We send our request in the getCities () method and use the Observable data service on the incoming stream, respectively:
    • We add a 2 second delay only for the test
    • We are pushing the incoming stream directly to the screen do (console.log)
    • We are converting the incoming Json string expression to a Json object expression. (Map)
    • We print the converted statement back to the console.
City.ts I create the City model class. The service will rotate the sequence of this model.

export class City {
    ID:number;
    name:string;
    country:string;
}

Step 5:

App.component.ts - Component to use the service


import { Component,OnInit,Input } from '@angular/core';
import { CitiesService } from './cities.service';
import { City } from './city';
import { Observable } from 'rxjs/Rx';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
  title = 'City App';
  cities:City[];

  constructor(public _cityService:CitiesService){}

  ngOnInit(){
    this._cityService.getCities()
    .subscribe(
        cities => (this.cities = cities) 
    );
  }
}
  • We use the ngOnInit method which will be called after the Component is created.
  • Here we are subscribing to the getCities method of the service (Observer or Subscriber) so that we can see the return data from Observable. We are throwing the return versi cities array.

Step 6:

App.component.html - We are printing data on the screen.


<div *ngIf="cities as city; else loading" id="cities">
 <ul>
  <li *ngFor="let city of cities">
    <span class="idtext">{{city.ID}}</span> -- {{city.name}} -- {{city.country}}
  </li>
 </ul>
</div>
<ng-template  #loading>
  <div class="loading">
    <img src="assets/images/preloader.gif">
  </div>
</ng-template>
  • We use the if else structure that comes with Angular 4.
  • If you do not press the screen when cities are available, we show another picture with ng-template.
  • Ng-template 'with #loading (template variable).

Step 7:

Building client code


ng build --prod
  • In the Console we enter the above command to make the project ready for presentation.
  • This will do all the optimizations. (Compression, merge css, js, etc.)
  • The resulting files will be placed under dist / under the project folder. These files are in the php project folder.
  • Index.html and specify your php project root directory at <base href = "/ php-angular-backend /"> . If this is not important, the project will not work.

Res 7.1 Project Structure

Step 8:

Route URLs to index.html

Create a .htaccess file in the main directory of the php folder and enter the following commands.

DirectoryIndex index.html

<IfModule mod_rewrite.c>
    Options -Indexes +FollowSymlinks
    RewriteEngine On

    
    RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
    RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d
    RewriteRule ^ - [L]
   
    RewriteCond %{REQUEST_URI} ^.*/$
    RewriteCond %{REQUEST_URI} !^/$
    RewriteRule ^(.*)/$ $1 [R,QSA,L]
    
    RewriteRule ^ index.html [L]
 
</IfModule>
  • The incoming requests will be collected in index.html.
  • The above commands are sufficient if you do not perform the router operation but assume that we will.

Note (Seo) : Google can directly index Angular pages. But the bottom pages can get in trouble. For now, you need to add each sub-page via Fetch as Google. Facebook Comment Api is not a problem to use, but Facebook Share is difficult to share dynamic content. In such cases, server rendering is required.
You can look at the demo of the application .

4 comments:

  1. Hi, thank you for your tutorial. However, when I reload the page I get error 404 Object not found

    ReplyDelete
    Replies
    1. sorry for late reply pls check this link https://github.com/angular/angular/issues/11884

      Delete
  2. It's very good. Could you please send me link or complete code of this. Thank you.

    ReplyDelete
  3. Demo not working .. Please send me alternative link ?

    ReplyDelete