0

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 ???
            });

 };
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567

2 Answers2

1

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')
               );
    }

}
micronyks
  • 54,797
  • 15
  • 112
  • 146
0

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

Community
  • 1
  • 1
Pardeep Jain
  • 84,110
  • 37
  • 165
  • 215
  • Thank, you are help me. But what's the difference between your version and the previous answer? – Sergey Bugai Jun 06 '16 at 21:11
  • difference is i have posted working example for better understanding, also provided correct way to provide headers, body and all while using http, provide link for step by step working for http in angular2 – Pardeep Jain Jun 07 '16 at 05:07