Skip to content

Instantly share code, notes, and snippets.

@kevinchisholm
Last active January 5, 2018 09:46
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/24ab3ad70759d3d0af227ca087ec4d6d to your computer and use it in GitHub Desktop.
Save kevinchisholm/24ab3ad70759d3d0af227ca087ec4d6d to your computer and use it in GitHub Desktop.
Angular HTTP get basics
import {Component} 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';
@Component({
selector: 'home',
templateUrl: 'src/home/home.html',
styleUrls: ['src/home/home.css']
})
export class HomeComponent {
//this contains the "packages" that appears in the UI
destinations: Array<any> = [];
constructor(private http: Http) {}
//when the component is initialized
public ngOnInit () {
//wait one second
setTimeout(() => {
//load packages
this.loadPackages();
}, 1000);
}
loadPackages () {
//reference the http service
this.http
//make the http GET request
.get('https://api.myjson.com/bins/1g87r')
//convert it to JSON
.map((res: any) => res.json())
//subscribe to this JSON
.subscribe ((data: any) => {
//set the "packages" in the UI
this.destinations = data;
}
);
}
}
<section class="page-content">
<div class="destinations-container">
<h2>Packages</h2>
<div>
<img *ngIf='!destinations.length' style="display: block;width: 120px;margin: 50px auto;" class="ajax-loader-boot" src="images/ajax-loader-ellipsis.gif" alt="">
</div>
<ul class="destinations">
<li *ngFor="let destination of destinations" class="destination">
<div class="box destination-wrapper">
<span class="flag {{destination.countryCode}}"></span>
<span><strong>{{destination.name}}</strong> </span>
<span>{{destination.duration}} for <span class="currency">$</span><span class="price">{{destination.price}}</span></span>
</div>
</li>
</ul>
</div>
</section>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment