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

Angular2 Tutorial: Creating Custom Pipes Angular 2 Pipes provide us a very simple way to transform/format the data displayed by our application, there are some built-in pipes we can use, but sometimes they don't meet our needs, that's when we have to create custom pipes. This will be a very quick tutorial in which I'll give you an example ...
Angular 2 Tutorial: Adding HotKeys (Keyboard shortcuts) to a Component Arguably hotkeys can substantially increase the usability of an application, the less the users have to touch the mouse the better will be their experience with the application. Luckily for us there is a very easy way of defining hotkeys on angular2, which is by adding a listener to the host comp...
Angular2 Forms Tutorial: Validating Required Fields Angular2 Form Validation In this tutorial I'll give you a simple example of how to validate a form with angular2. As you can see in the image, the example consists of a form with two required fields, the form can only be submitted if both fields are valid. I'm going to use bootstrap for styli...
Angular2 error: Error in ./AppComponent class AppComponent_Host – inline template:0:0 caused b... If you're seeing this error when you run your application it's probably because you're trying to use http.get without importing the HttpModule. This is what the error looks like on the browser console: core.umd.js:5995 EXCEPTION: Error in ./AppComponent class AppComponent_Host - inline temp...

12 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

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>