Angular 4 Data Retrieve Use Server PHP


all_list.php

<?php 
header("Access-Control-Allow-Origin: *");

$dbLink = mysql_connect('localhost','root','');
mysql_select_db('sakila');
$sql = "SELECT * FROM actor";
$result = mysql_query($sql,$dbLink);
$data = array();
while($row = mysql_fetch_array($result)){
$data[] = $row;
}
echo json_encode($data);
?>

data.component.ts

import { Injectable } from '@angular/core';
import {HttpModule, Http,Response} from '@angular/http'; 
import 'rxjs/add/operator/map'


@Injectable()
export class DataService {

http: Http;
posts_Url: string = 'http://localhost/dev2017/angular/ng4-crud/php_code/all_list.php';
constructor(public _http: Http){ 
this.http = _http;    
}
getUserPosts(){ 
return this.http.get(this.posts_Url) .map((res: Response) => { 
return res.json(); 
}
); 
}
}

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';

import { AppComponent } from './app.component';
import { DataService } from './data.service';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule
  ],
  providers: [DataService],
  bootstrap: [AppComponent]
})
export class AppModule { }

app.component.ts

import { Component } from '@angular/core';
import { DataService } from './data.service';
import {Http, Response} from '@angular/http';

@Component({
selector: 'app-root',
// templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
template: `
<h1>{{title}}</h1>

<table border = 1>
<tr>
<th>Actor Id</th>
<th>First Name</th>
<th>Last Name</th>
</tr>
<tr *ngFor="let post of data">
<td>{{post.actor_id}}</td>
<td>{{post.first_name}}</td>
<td>{{post.last_name}}</td>
</tr>
</table>
`,
})
export class AppComponent {
title = 'app works!';
private data;
constructor(private _postService: DataService) { }
posts:Object = [];
ngOnInit() {
this.getPosts();
}
getPosts() {
this._postService.getUserPosts()
.subscribe(arg => this.data = arg);
};
}

-------------------------
Screenshot

 








Share on Google Plus

About Ram Pukar

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment

0 comments:

Post a Comment