256
Hello to all, welcome to therichpost.com. In this post, I will tell you, Angular6 httpclient Working Example.
Angular6 is growing very fastly day by day. In this post, I am showing the HttpClient example to get data from backend. I have used Php Mysql as backend.
Here is working image after getting data:
Here is working and tested code:
1. Here is below code and you need to add this into your app.component.ts file:
import {Component, OnInit} from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { posts: any; constructor(private http: HttpClient) { this.http.get('http://localhost/mypage.php').subscribe(data => { this.posts = data; // show data in console console.log(this.posts); }); } title = 'my-angular-app'; }
2. Here is the below code and you need to add this into your app.module.ts file:
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; import { HttpClientModule } from '@angular/common/http'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, HttpClientModule, ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
3. Here is my php file code and you can modify it by your requirement:
<?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"); $conn = new mysqli('localhost','root','root','user'); $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;
And now you are done. if you have any query related to this post then you can ask questions or comment below.
1 comment
Import paths
For JavaScript developers, the general rule is as follows:
rxjs: Creation methods, types, schedulers and utilities
import { Observable, Subject, asapScheduler, pipe, of, from, interval, merge, fromEvent } from ‘rxjs’;
rxjs/operators: All pipeable operators:
import { map, filter, scan } from ‘rxjs/operators’;
rxjs/webSocket: The web socket subject implementation
import { webSocket } from ‘rxjs/webSocket’;
rxjs/ajax: The Rx ajax implementation
import { ajax } from ‘rxjs/ajax’;
rxjs/testing: The testing utilities
import { TestScheduler } from ‘rxjs/testing’;
and for backward compatability you can use rxjs-compat