Http and Observable in Angular2

 
//app.module.ts
import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpModule} from '@angular/http';
import { studentListComponent } from './student.List';
import { AppComponent }   from './app.component';

@NgModule({
  imports:      [ BrowserModule,HttpModule ],
  declarations: [ AppComponent,studentListComponent],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }
 
//app.component.ts
import { Component } from '@angular/core';
import { studentService } from './student.Service';

@Component({
  selector: 'my-app',
  template: '<student></student>',
  providers:[studentService]
})
export class AppComponent { 

}
 
//student.Service.ts
import {Injectable, Inject} from '@angular/core';
import {Http, Response} from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
@Injectable();
export class studentService{
	
	private _url:string = "http://localhost:3000/app/test.json";
	constructor(@Inject(Http) private _http: Http){}
	getStudent(){
		return this._http.get(this._url)
		.map((res: Response) => res.json());
	}
}
 
//student.List.ts
import { Component, OnInit } from '@angular/core';
import { studentService } from './student.Service';
@Component({
	selector:"student",
	template:`
		<h1>First Student List View</h1>
		<ul *ngFor="let students of student">
			<li>{{students.name}} Age {{students.age}} </li>
		</ul>
	`
})


export class studentListComponent implements OnInit  {
	student = [];
	constructor(private _student:studentService){}
	ngOnInit(){
		this._student.getStudent()
		.subscribe(studentData => this.student = studentData)

	}
}import { Component, OnInit } from '@angular/core';
import { studentService } from './student.Service';
@Component({
	selector:"student",
	template:`
		<h1>First Student List View</h1>
		<ul *ngFor="let students of student">
			<li>{{students.name}} Age {{students.age}} </li>
		</ul>
	`
})


export class studentListComponent implements OnInit  {
	student = [];
	constructor(private _student:studentService){}
	ngOnInit(){
		this._student.getStudent()
		.subscribe(studentData => this.student = studentData)

	}
}
 
//test.json
[
    {"id": 1, "name": "Sam", "gender": "Male", "age": 5},
    {"id": 2, "name": "Tod", "gender": "Male", "age": 7},
    {"id": 3, "name": "Samanta", "gender": "Female", "age": 7},
    {"id": 3, "name": "Juli", "gender": "Female", "age": 8},
    {"id": 4, "name": "Mark", "gender": "Male", "age": 9}

]

Leave a Reply

Your email address will not be published. Required fields are marked *