Connecting to Server
Http service provides following methods...
<script src=“node_modules/angular2/bundles/http.dev.js”/>
API - /api/books
get() // get all/single resource
post() // add data to resource
put() // update the resource
patch() // partial update of resource
delete() // delete resource
head() // get metadata of resource, want to just check existance of resource
Http Class
http.get(url).map(response => response.json());
http.post(url, JSON.stringify(obj)).map(response => response.json());
Using Http Class
Create Service
import {Http} from 'angular2/http';
@Injectable()
export class PostService
{
constructor(private _http: Http) {}
getPosts()
{
return this._http.get(url).map(res => res.json());
}
}
Using the Service
import {HTTP_PROVIDERS} from 'angular2/core';
@Component({
providers: [PostService, HTTP_PROVIDERS]
})
export class AppComponent implements OnInit {
posts: any[];
ngOnInit()
{
this._postService.getPosts()
.subscribe(posts => this.posts = posts);
}
}
Note
HTTP_PROVIDERS
includes all classes on which Http depends on
Adding Custom Request Headers
var headers = new Headers({
“key”: “value”
});
var options = new RequestOptions({
headers: headers
});
http.get(url, options);
Last updated
Was this helpful?