Reputation: 3
I have service and method that get data from API. How can i take this data in controller?
getRoom(id) {
let headers = new Headers({ 'Content-Type': 'application/json' })
let body = JSON.stringify({id});
let options = new RequestOptions({ headers: headers });
this._http.post('/api/forum/findRoom', body, options)
// .map(res => console.log(res))
.subscribe(res => {
// return ???
});
};
Upvotes: 0
Views: 84
Reputation: 86730
As you haven't posted proper answer without showing your imports firstly please have a look at here
Now make sure you have imported all required dependencies for making http request. now you can use this code as shared_service
getRoom(id) {
let headers = new Headers();
headers.append("Content-Type", 'application/json'); // header portion ends here
let body = JSON.stringify({id}); // body ends here
let options = new RequestOptions({
method: RequestMethod.Post,
url: '/api/forum/findRoom',
headers: headers,
body: body
})
return this.http.request(new Request(options))
.map((res: Response) => {
if (res) {
return [{ status: res.status, json: res.json() }]
}
});
};
Now this will create your shared service for making post request. now whenever you required to take data(response) in the controller (class). than you just need to import this file and call the method named getRoom()
using class name as prefix. and then subscribe there to get data like this :-
class_name.getRoom('your_data')
.subscribe((data) => { console.log(data);}, <------subscribe to the service
err=>console.log(err),
()=>console.log('done'));
I hope this clears everything related to Http. if you have any query comment here.
also to get Request using http see here Working Example of Http
Upvotes: 0
Reputation: 55443
NOTE: please import required things which are not shown here.
export class sharedService{
getRoom(id) {
let headers = new Headers({ 'Content-Type': 'application/json' })
let body = JSON.stringify({id});
let options = new RequestOptions({ headers: headers });
return this._http.post('/api/forum/findRoom', body, options) <----return keyword
.map(res => console.log(res))
}
}
main.ts
import {AppComponent} from './AppComponent' <---path to AppComponent
import {sharedService} from './sharedService' <--- path to sharedService
bootstrap(AppComponent,[sharedService]); <----this injection will create single instance of sharedService.
AppComponent.ts
import {sharedService} from './sharedService' <---path to sharedService
export class AppComponent
{
constructor(private ss:sharedService) <--- dependency injection
{
}
ngOnInit(){
ss.getRoom(2).subscribe( <------subscribe to the service
(data) => {
this.result=data;
},
err=>console.log(err),
()=>console.log('done')
);
}
}
Upvotes: 1