Skip to content

Instantly share code, notes, and snippets.

@aaronksaunders
Last active November 15, 2017 16:14
Show Gist options
  • Save aaronksaunders/039c3f02f27c17e3ac1dd2ed15e50edb to your computer and use it in GitHub Desktop.
Save aaronksaunders/039c3f02f27c17e3ac1dd2ed15e50edb to your computer and use it in GitHub Desktop.
Angular2 Http Example
<div class="preventoverflow">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/es6-shim/0.34.0/es6-shim.js"></script>
<script src="https://code.angularjs.org/2.0.0-beta.14/angular2-polyfills.js"></script>
<script src="https://code.angularjs.org/tools/system.js"></script>
<script src="https://code.angularjs.org/2.0.0-beta.14/Rx.js"></script>
<script src="https://code.angularjs.org/2.0.0-beta.14/angular2.js"></script>
<script src="https://code.angularjs.org/2.0.0-beta.14/http.js"></script>
<script src="https://code.angularjs.org/2.0.0-beta.14/router.dev.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
System.config({
map: {
app: 'https://codepen.io/aaronksaunders/pen/EKRJRJ.js'
},
meta: {
'*.js': {
format: 'cjs'
}
},
packages: {
app: {
format: 'register',
defaultExtension: 'js'
}
}
});
System.import('app')
.catch(console.error.bind(console));
</script>
</head>
<my-app>Loading...</my-app>
</div>
import { Http, URLSearchParams } from "angular2/http";
import { HTTP_PROVIDERS } from "angular2/http";
import {OnInit, Injectable, Component} from "angular2/core";
import {bootstrap} from 'angular2/platform/browser';
import 'rxjs/Rx';
@Injectable()
export class DataService {
private BASE_URL = 'https://api.nutritionix.com/v1_1/search/'; // URL to web api
private APP_ID = '8abbcd8e';
private API_KEY = '36e8d264537037ee7e832a41902ffe57';
/*this line is necessary to make the constructor work*/
static get parameters() {
return [[Http]];
}
/**/
constructor(private http: Http) {
}
getSomeData(_searchString) {
let params: URLSearchParams = new URLSearchParams();
params.set('appId', this.APP_ID);
params.set('appKey', this.API_KEY);
let url = this.BASE_URL + _searchString;
return this.http.get(url, { search: params })
.map(res => res.json().hits);
}
}
@Component({
selector: 'my-app',
template: `
<div>
<div *ngFor="#item of resultArray">
{{item.fields.item_name}}
</div>
</div> `,
providers: [DataService]
})
export class AppComponent implements OnInit {
resultArray
/**this line is necessary to make the constructor work**/
static get parameters() {
return [[DataService]];
}
/**/
constructor(public _dataService : DataService) {
this.arraytorender=[]
}
ngOnInit():any {
this._dataService.getSomeData().subscribe(response => {
console.log(response)
this.resultArray = response
});
}
}
bootstrap(AppComponent, [HTTP_PROVIDERS])
.catch(err => console.error(err));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment