Categories

Friday, November 22, 2024
#919814419350 therichposts@gmail.com
Angular 8Angular 9MysqlPhp

Angular 9 services working example with php mysql

angular 9 services with php mysql data

Hello to all, welcome again on therichpost.com. In this post, I will tell you, Angular 9 services working example with php mysql.

Post Working:

In this post, I am showing php mysql data into my angular 9 application with the help of angular services.

Here is the working code snippet and please use carefully:

1. Here is the code, you need to add into your app.module.ts file:

...
import { HttpClientModule } from '@angular/common/http';
...
 imports: [
    ...
  HttpClientModule
  ],

 

2. Now you need to create new file app/app.service.ts and add below code inside it:

import { Injectable } from '@angular/core'; 
import { HttpClient } from '@angular/common/http';
@Injectable()
export class appService { 

constructor(private http:HttpClient) { }

public getPosts()
    {
        return this.http.get('http://localhost/mypage.php');
    }
}

 

3. Now you need to add below code into app.component.ts file:

...
import { appService } from './app.service'; 
@Component({
  ...
  providers: [appService]
})
export class AppComponent {
  ...
  data = [];
  constructor(private appservice: appService) {} 
  ngOnInit() {
  
  
  this.appservice.getPosts().subscribe((ret: any[])=>{
      console.log(ret);
      this.data = ret;
    })

  }
}

 

4. Now you need to add below code into app.component.html file:

<table class="table">
  <thead>
  <tr>
  <th>ID</th>
  <th>NAME</th>
  <th>Email</th>
  </tr>
  </thead>
  <tbody>
  <tr *ngFor="let post of data">
  <td>{{ post.id }}</td>
  <td>{{ post.firstname }}</td>
  <td>{{ post.email }}</td>
  </tr>
  </tbody>
  </table>

 

5. Here is you php file mypage.php code:

<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: PUT, GET, POST");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");

$sql = "SELECT * FROM userdata";
$result = $conn->query($sql);
$myArr = array();
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$myArr[] = $row;
}
} else {
echo "0 results";
}
$myJSON = json_encode($myArr);
echo $myJSON;

?>

 

If you have any kind of query then please do comment below.

Jassa

Thank you

therichpost
the authortherichpost
Hello to all. Welcome to therichpost.com. Myself Ajay Malhotra and I am freelance full stack developer. I love coding. I know WordPress, Core php, Angularjs, Angular 19, MedusaJs, Next.js, Bootstrap 5, Nodejs, Laravel, Codeigniter, Shopify, Squarespace, jQuery, Google Map Api, Vuejs, Reactjs, Big commerce etc.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.