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

Tutorial: Creating an Angular2 Autocomplete Angular 2 Autocomplete Before we begin I just want to say that I'm not going to use any third-party component for this tutorial, I'm going to create an autocomplete from scratch, my goal is to just make it show the suggestions and allow the user to select one, but if you need more advanced featu...
Creating an Angular2 Datatable from Scratch PART 2: Filtering the Data Continuing from where we stopped at Part 1, today we're going to add the filter functionality to the table, but before we start let's do some styling. I'm going to use Bootstrap, but if you don't want you don't have to, feel free to style your component as you like. But if you decide to use Bootstra...
Tutorial: Creating RESTful Web Services with EJB 3.1 RESTful web services has gained a lot of acceptance across the web, they are basically web services that follows the REST guidelines. In this short tutorial I’m going to create a very simple Hello World application that implements a RESTful Web Service using EJB 3.1. I’m assuming that you already...
Creating an Angular2 Image Gallery In order to make this tutorial easier for beginners I'm going to start by creating the simplest possible gallery, from there I'm going to develop and add more functionalities to it, which will increasingly make the gallery more complex as we proceed. If you are already familiar and have some experie...

13 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 ..

  3. Prasenjit Aluni

    Hi,
    I install Angular 2 quickstart in my project, its works fine. but when paste above code in my main.ts and app.component.ts file its stop working, please give any idea to solve the problem

  4. Roy Mashiah

    Hi,

    Is it safe to keep this line below on production :
    header(“Access-Control-Allow-Origin: *”);
    ??

    Thanks

Leave a Reply to Mani Cancel 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>