Skip to content

Instantly share code, notes, and snippets.

@kevinchisholm
Last active December 24, 2017 15:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kevinchisholm/4f89d683211a200f77658a0c01b53270 to your computer and use it in GitHub Desktop.
Save kevinchisholm/4f89d683211a200f77658a0c01b53270 to your computer and use it in GitHub Desktop.
Angular2 HTTP Observables in Five Minutes

RxJS Logo

Example code for the blog post: Angular2 HTTP Observables in Five Minutes

import {Package} from './package';
import {Injectable} from '@angular/core';
import {Http, Headers, BaseRequestOptions, } from '@angular/http';
import 'rxjs/add/operator/map';
import {Subject} from 'rxjs/Subject';
import {BehaviorSubject} from 'rxjs/BehaviorSubject';
import {Observable} from 'rxjs/Observable';
@Injectable()
export class PackageService {
packageData: Subject<Array<Package>> = new BehaviorSubject<Array<Package>>([]);
constructor(private http: Http) {
}
loadAllPackages () {
this.http
.get('https://api.myjson.com/bins/1g87r')
.map((res: any) => {
return res.json();
})
.subscribe (
(data: any) => {
this.packageData.next(data);
},
(err: any) => console.error("loadAllPackages: ERROR"),
() => console.log("loadAllPackages: always")
);
}
}
import {Component} from '@angular/core';
import {PackageService} from './package.service';
import {Package} from './package';
import * as _ from 'lodash';
@Component({
selector: 'packages',
templateUrl: 'src/packages/packages.html',
providers: [PackageService],
styleUrls: ['src/packages/packages.css']
})
export class PackagesComponent {
destinations: Array = [];
constructor(private packageService: PackageService) {
}
public ngOnInit () {
//subscribe to the packageData stream
this
.packageService
.packageData
.subscribe((packages: Array) => {
//mimic a slow connection
setTimeout(() => {
//set packages
this.destinations = packages;
//sort the data
this.sortByPrice();
}, 1500);
});
//make the http request
this.packageService.loadAllPackages();
}
refreshData() {
//re-set the ui
this.destinations.length = 0;
//make the http request
this.packageService.loadAllPackages();
}
sortByPrice () {
this.destinations = _.sortBy(
this.destinations, function(d: any) {
return parseInt(d['price'].replace(',', ''), 10);
}
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment