Get Service (JSON) Data to render from URL. (Source: http://keysandstrokes.info/how-to-retrieve-data-from-the-database-using-angular2/)
import {HttpModule, Http, Response} from '@angular/http';
import {Injectable} from '@angular/core';
import 'rxjs/add/operator/map'
@Injectable()
export class PostService {
http: Http;
posts_Url = 'https://jsonplaceholder.typicode.com/posts';
constructor(public _http: Http) {
this.http = _http;
}
getUserPosts() {
return this.http.get(this.posts_Url) .map((res: Response) => res.json() );
}
}
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms'; // <-- NgModel lives here
import { HttpModule } from '@angular/http';
import { AppComponent } from './app.component';
import { PostService } from './post.service';
@NgModule({
declarations: [
AppComponent,
],
imports: [
BrowserModule,
FormsModule, // <-- import the FormsModule before binding with [(ngModel)]
HttpModule
],
providers: [PostService],
bootstrap: [AppComponent]
})
export class AppModule { }
import { Component, OnInit } from '@angular/core';
import { PostService } from './post.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
constructor(private _postService: PostService) { }
posts:Object = [];
getPosts() {
this._postService.getUserPosts().subscribe(arg => this.posts = arg);
};
ngOnInit() {
this.getPosts();
}
}
<ul>
<li *ngFor="let post of posts">
{{ post.id }} - {{ post.title }}
</li>
</ul>