Mobile app request JSON API
Wichan Thumthong
crate services
app/services/reddit.service.ts
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/rx';
@Injectable()
export class RedditService{
http:any;
baseUrl: String;
constructor(http:Http){
this.http = http;
this.baseUrl = 'https://www.reddit.com/r';
}
getPosts(category, limit){
return this.http.get(this.baseUrl+'/'+category+'/top.json?limit='+limit) .map(res => res.json());
} }
App.component.ts
import { RedditService } from ‘./services/reddit.service';
@Component({
templateUrl: 'app.html', providers : [RedditService]
})
import { HttpModule } from ‘@angular/http';
imports: [
BrowserModule,
IonicModule.forRoot(MyApp), HttpModule
],
App.module.ts
home.ts
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { RedditService } from '../../app/services/reddit.service';
@Component({
selector: 'page-home', templateUrl: 'home.html' })
export class HomePage { items: any;
constructor(public navCtrl: NavController, private redditservice:RedditService) { }
ngOnInit(){
this.getPosts('sports', 5);
}
getPosts(category, limit){
this.redditservice.getPosts(category, limit).subscribe(response => { this.items = response.data.children; });
} }
home.html
<ion-header>
<ion-navbar>
<ion-title>Home</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<ion-list>
<ion-item *ngFor="let item of items">
<ion-thumbnail item-left>
<img src="{{item.data.thumbnail}}">
</ion-thumbnail>
<h2>{{item.data.title}}</h2>
<p>
<ion-icon name="thumbs-up"> {{item.data.score}}</ion-icon>
<ion-icon name="chatboxes"> {{item.data.num_comments}}</ion-icon>
</p>
<button ion-button item-right color="secondary">VIEW</button>
</ion-item>
</ion-list>