In angular2 we are using services to interact with the server using API calls.
get(url
:string,
options
?:RequestOptionsArgs
)
post(url
:string,
body
:any,
options
?:RequestOptionsArgs
)
put(url
:string,
body
:any,
options
?:RequestOptionsArgs
)
The @Injectable()
decorator is needed when a Service needs dependencies injected to its constructor.
Example:
user.service.ts
import{Injectable} from '@angular/core';
import {Http, Response}from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class UserService{
constructor(
private http:Http
){}
getUser(){
return this.http.get(`https://conduit.productionready.io/api/profiles/eric`)
.map((res:Response)=>res.json());
}
}
Users-list.component.ts
Import { Component } from '@angular/core';
Import { UserService } from './shared/index';
@Component({
selector: 'home-page',
template:` Load profile {{ profile | json }} `
});
export class HomeComponent{
Profile: any;
constructor(private userService:UserService){
}
loadUser(){
this.userService.getUser().subscribe(data=>this.profile=data);
}
}
Note:
If you want to call Service from your component you must import that service class into component.ts page and imported service class name should be define in constructor to utilize the service in your page and also import Service class name into modules.ts page and define that service name in providers array.