Angular 2 http post example

You can create a simple HTTP Post 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 post(userObj) {
             return this.http.post('http://bospp.com/post', JSON.stringify(userObj) {
                 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){

         }

         createUser() {
               let user = {
                    "firstName": "Rahul",
                    "lastName": "Jain"
               };
               this.userService.post(user).subscribe(resp => {
               user = resp.body['userObj'];
        }

}

No comments:

Post a Comment