Part 10 : Services in Angular 2 http get post
In this tutorial we will be studying services in angular 2 project.
How to implement http get post request in angular 2.
How to receive json data and binf it to the view so that it is visible in browser.
Click here to download complete project
App Module Code
How to implement http get post request in angular 2.
How to receive json data and binf it to the view so that it is visible in browser.
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpModule } from '@angular/http';
import { FormsModule } from '@angular/forms';
import { HomeComponent } from '../../Views/Home/home.component';
import { BasicService } from '../../Service/Basic.service';
@NgModule({
imports: [ BrowserModule, HttpModule, FormsModule ],
declarations: [ HomeComponent ],
bootstrap: [ HomeComponent ],
providers: [BasicService]
})
export class AppModule { }
Service Code
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map'
@Injectable()
export class BasicService {
constructor(private http: Http) {
}
GetPosts() {
return this.http.get('https://jsonplaceholder.typicode.com/posts').map(result => result.json());
}
GetPostAsPerId(Id : any){
return this.http.get('https://jsonplaceholder.typicode.com/posts/' + Id).map(result => result.json());
}
}
Home Component Code
import { Component } from '@angular/core';
import { BasicService } from '../../Service/Basic.service';
@Component({
selector: 'my-app',
template: `<h1>Hello {{name}}</h1><hr/>
<div style="height:200px; overflow:auto;">
<table *ngFor="let item of data" >
<tr><td>Id</td><td>{{item.id}}</td></tr>
<tr><td>UserId</td><td>{{item.userId}}</td></tr>
<tr><td>Title</td><td>{{item.title}}</td></tr>
<tr><td>Body</td><td>{{item.body}}</td></tr>
</table>
</div>
<hr/>
<input [(ngModel)]="PostId" name="PostId" />
<button (click)='GetPost()' >Get Post</button>
<table>
<tr><td>Id</td><td>{{SinglePost.id}}</td></tr>
<tr><td>UserId</td><td>{{SinglePost.userId}}</td></tr>
<tr><td>Title</td><td>{{SinglePost.title}}</td></tr>
<tr><td>Body</td><td>{{SinglePost.body}}</td></tr>
</table>
`,
})
export class HomeComponent {
name: string;
data: any;
PostId: any;
SinglePost: any;
constructor(private MyService: BasicService) {
this.name = "Angular Service";
this.MyService.GetPosts().subscribe(posts => { this.data = posts });
this.PostId = "0";
this.SinglePost = {
id:'',
userId:'',
title:'',
body :''
}
}
GetPost() {
this.MyService.GetPostAsPerId(this.PostId).subscribe(post => { this.SinglePost = post; });
}
}
No comments