angular 2 http get example

You can create a simple HTTP Get service in Angular 2 like below:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams} from '@angular/common/http';
import { URLSearchParams } from '@angular/http';

@Injectable()
export class UserService {

       constructor(private http: HttpClient) {

        }

        public get(id: string) {
             return this.http.get('http://bospp.com/get/' + id, {
                 observe: 'response'
             });
        }
}

In Component you can call this service like:

@Component({
       selector: 'user-page',
       templateUrl: './user-page.html',
      providers: [UserService]
})


export class UserPage implements OnInit {

         constructor(private userService: UserService){

         }

         getUser() {
               const userID = '101';
               let user = null;
               this.userService.get(userID).subscribe(resp => {
               user = resp.body['userObj'];
        }

}

No comments:

Post a Comment