Integrating an Angular2 app with a PHP app

In this tutorial I’m going to show you how to use Angular2 Http client to communicate with an php application. I don’t want this to be a very long post, so I’m going to make everything as simple as possible.

The first step, of course, is to provide a php web service, it doesn’t need to be anything sophisticated, just returning a json dataset will do for now. We can achieve this by creating an php app with just an index.php file containing the following code:

<?php
 	header("Access-Control-Allow-Origin: *");
	$data = array(
		array('id' => '1','first_name' => 'Cynthia'),
		array('id' => '2','first_name' => 'Keith'),
		array('id' => '3','first_name' => 'Robert'),
		array('id' => '4','first_name' => 'Theresa'),
		array('id' => '5','first_name' => 'Margaret')
	);
 
	echo json_encode($data);
?>

As you can see, in this file I’m just manually creating my dataset. Note that I’ve included the line header("Access-Control-Allow-Origin: *"); at the beginning, by doing this I’m avoiding the Cross-Origin Request Blocked error, which is a very common error for people who are getting started with web services, no matter which programming language you are using, if you don’t allow other applications to access your service you’ll see this error.

Now let’s get started with our angular2 application, you probably already have everything set up, but if you don’t, just follow the instructions on the Angular2 Quickstart to create an empty project.

We’re going to need Http Client to be able to send requests to our server, in order to use it on our project we have to register it as a service provider on our main.ts:

import { bootstrap }    from '@angular/platform-browser-dynamic';
import {HTTP_PROVIDERS} from '@angular/http';
import { AppComponent } from './app.component';
bootstrap(AppComponent, [HTTP_PROVIDERS]);

Next let’s create the component, if you followed the instructions from the angular2 quickstart you already have the app.component.ts in your project, just open this file and paste the following code into it:

import {Http, Response} from '@angular/http';
import {Injectable, Component } from '@angular/core';
 
@Component({
  selector: 'my-app',
  template: `<ul>
		<li *ngFor="let person of data">
		   {{person.id}} - {{person.first_name}}
		</li>
	     </ul>`
})
export class AppComponent { 
 
    private data;
 
    constructor(private http:Http){
    }
 
    ngOnInit(){
    	this.getData();
    }
 
    getData(){
        this.http.get('http://localhost/AngularWithPhpTest/')
        		.subscribe(res => this.data = res.json());
    }
}

Most of what’s in this code probably isn’t new for you, so I won’t bother to explain all the basic things again. What matters here is the getData() method, that’s where we’re getting the data from that php web service we created at the beginning.

Now let’s see how it actually works, if you take a look at the code you’ll see that I’ve used two functions to be able to get the data: get() and subscribe(). The first receives the web service url and calls the server to get the data, while the second one specifies the actions that should be taken when it receives the response, in this case I’m just assigning the received data to the this.data variable, pretty simple right?

This was a really simple example, but feel free to leave a comment if you have any doubts. I showed you just how to load a dataset, but there are a lot more that could be done here, you don’t necessary have to get a json dataset as a result, it could be anything you want, and you could also add some parameters to your url and read them on the server-side, that would allow you to send information back and forth between your applications.

Recommended for you

8 comments on “Integrating an Angular2 app with a PHP app

  1. Mani

    Hi,

    when i past your code in my project , i didn’t get any output and i have pasted your main.ts code in my main.ts it shows some errors like “deprecated symbols used consult docs…..” one more doubt is whatwe have to pass in this.http.get(”), you gave some path but i didnt understand what it seems
    this is my main.ts file

    /**
     * Created by karthika on 8/17/2016.
     */
    import { bootstrap }    from '@angular/platform-browser-dynamic';
    import {HTTP_PROVIDERS} from '@angular/http';
    import { AppComponent } from './app.component';
    bootstrap(AppComponent, [HTTP_PROVIDERS]);
     
     
    app.component.ts
     
    import {Http, Response} from '@angular/http';
    import {Injectable, Component } from '@angular/core';
     
    @Component({
        selector: 'my-app',
        template: `{{title}}
     
    		   {{person.id}}
     
    	     `
    })
    export class AppComponent {
     
        private data;
        title="hai how are you";
     
        constructor(private http:Http){
        }
     
        ngOnInit(){
            this.getData();
        }
     
        getData(){
            this.http.get('http://localhost/AngularWithPhpTest/')
                .subscribe(res =&gt; this.data = res.json());
        }
    }

    thank you

      1. Tyler Christian

        Yeah, you need to use HttpModule from ‘@angular/http now rather than HTTP_PROVIDERS, with version 2.0 that Quickstart uses ( the version is in package.json under dependencies ).

  2. Kishore Kumar B

    Thanks man.. I’m doing a project which is an integration of angular 2 and laravel.. I don’t know how to pass the data from angular2 service to laravel which needs to be inserted in mysql. by using angular 2 SERVICES, I post the data but its struggle for me handle it in laravel side to do DB operations.. please help me ..

Leave a Reply

Your email address will not be published. Required fields are marked *

Obs: Use the tag <pre lang="LANGUAGE"> to include code blocks to your comment.
Example: <pre lang="javascript"> console.log('Test'); </pre>