Posts Angular2 - Adding service to interact with a PHP web service
Post
Cancel

Angular2 - Adding service to interact with a PHP web service

Creating the first form

// http://blog.ng-book.com/the-ultimate-guide-to-forms-in-angular-2/ // https://angular.io/docs/ts/latest/guide/forms.html

When ngModel is without attribute value is #one-way data binding#

examples for #two-way data binding#

js//Example 1 <input [(ngmodel)]="person.firstName" name="first">

js//Example 2 <input [(ngmodel)]="person.firstName" [ngmodeloptions]="{standalone: true}">

x.module.ts must import **:

import { FormsModule } from ‘@angular/forms’;

x.component.html:

<form (ngsubmit)=””>tryLogin(myForm.value)” #myForm=”ngForm”>

<div layout=""></div>“column”>

<div flex=""></div>

“Username” name=“username” ngModel required>

<div flex=""></div>

“Password” name=“password” ngModel required>

“accent” type=“submit”>Log in

</form>

x.component.ts :

import { Component } from ‘@angular/core’;

@Component({

selector: ‘app-root’,

templateUrl: ’./x.component.html’,

styleUrls: [’./x.component.css’]

})

export class AppComponent {

tryLogin(form_data: any){

console.log(form_data);

console.log(form_data.username);

}

}

When click the Log in button

 

Adding service to interact with a PHP web service

Create a file service.ts

Angular2 automatically detects that the input is a raw object, adds the Content-Type : application/json.

Option1

let g = {

‘name’ : user,

‘password’ : password

}

let body = JSON.stringify(g);

return this.http.post(“http://localhost/login.php”, body);

Option2

let body = {

‘name’ : user,

‘password’ : password

}

return this.http.post(“http://localhost/login.php”, body);

Im using two servers (locahost:4200 and localhost (xampp)) – when using this option we have 2 calls to server, asking what the destination server supports. **Tested when the files are on the same server the call is one**

// http://stackoverflow.com/a/21783145

This is happening because Im using separated servers for the calls

“preflighted” requests first send an HTTP request by the OPTIONS method to the resource on the other domain, in order to determine whether the actual request is safe to send. Cross-site requests are preflighted like this since they may have implications to user data.

My login.php is as the following

<>

//not safe on live server

//header(‘Access-Control-Allow-Origin: *’);

//header(‘Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS’);

//header(‘Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token’);

if ($_SERVER[‘REQUEST_METHOD’] === ‘POST’) {

var_dump($_POST);

}

Using Option1 or Option2 the login.php cant handle it, is $_POST, but empty one.

The cause : // http://stackoverflow.com/a/20295138

When using Content-Type : application/json you will not be able to rely on $_POST being populated. $_POST is only populated for form-encoded content types.

modify the header

let g = {

‘name’ : user,

‘password’ : password

}

let body = JSON.stringify(g);

let headers = new Headers();

headers.append(‘Content-Type’, ‘application/x-www-form-urlencoded; charset=UTF-8’);

return this.http.post(‘http://localhost/login.php’,body, { headers });

Crazy ? The Angular json made array key J

Reconstructing login.php, **we can read the JSON

// http://php.net/manual/en/function.key.php // http://stackoverflow.com/a/467187 – What is the max key size for an array in PHP? - A quick test got me a key of 128mb no problem.

if ($_SERVER[‘REQUEST_METHOD’] ===‘POST’) {

$_POST = json_decode(key($_POST), true);

var_dump($_POST);

}

Many people mention to read the php://input (for sure Im not going with this) – http://stackoverflow.com/a/24140930

if ($_SERVER[‘REQUEST_METHOD’] == ‘POST’&& empty($_POST))

$_POST = json_decode(file_get_contents(‘php://input’), true);

[flavor1] Complete service.ts working with PHP

import { Injectable } from ‘@angular/core’;

import { Http, Headers } from ‘@angular/http’;

import ‘rxjs/Rx’;

@Injectable()

export class WebService {

constructor (private http: Http) {}

public loginUser(user:string, password:string) {

let g = {

‘name’ : user,

‘password’ : password

}

let body = JSON.stringify(g);

let headers = new Headers();

headers.append(‘Content-Type’, ‘application/x-www-form-urlencoded; charset=UTF-8’);

return this.http.post(‘http://localhost/login.php’, body, { headers });

}

}

[flavor2] Modify service.ts to serialize the objects (as jQuery.ajax doing till now), no PHP troubles.

// http://restlet.com/company/blog/2016/08/29/whats-new-in-the-http-module-of-angular-2/ // https://angular.io/docs/ts/latest/api/http/index/URLSearchParams-class.html

import { Injectable } from ‘@angular/core’;

import { Http, URLSearchParams } from ‘@angular/http’;

import ‘rxjs/Rx’;

@Injectable()

export class WebService {

constructor (private http: Http) {}

public loginUser(user:string, password:string) {

let body = new URLSearchParams();

body.set(‘name’, user);

body.set(‘password’, password);

return this.http.post(‘http://localhost/login.php’, body);

}

}

x.component.ts :

import { Component } from ‘@angular/core’;

import { WebService } from ’./service’;

@Component({

selector: ‘app-root’,

templateUrl: ’./app.component.html’,

styleUrls: [’./app.component.css’],

providers: [WebService]

})

export class AppComponent {

constructor(private webService: WebService) { }

tryLogin(form_data: any){

this.webService.loginUser(form_data.username, form_data.password).map(res => res.json()).subscribe((data)=> console.log(data), (err) => console.log(“error occured”, err));

console.log(form_data);

console.log(form_data.username);

}}

origin - http://www.pipiscrew.com/?p=7273 angular2-adding-service-to-interact-with-a-php-web-service

This post is licensed under CC BY 4.0 by the author.
Contents

Trending Tags