1

I'm testing this sample: http://plnkr.co/edit/WTu5G9db3p4pKzs0WvW6?p=preview.

This code, implements a login form with name, mail, profile. On clicking submit button, an alert appears on display with name and email fields.

saveUser() {
    if (this.userForm.dirty && this.userForm.valid) {
        alert(`Name: ${this.userForm.value.name} Email: ${this.userForm.value.email}`);
    }
}

On above, the saveUser function in app.component.ts. It executes the alert on clicking button. On saveUser function, I would like to invoke a POST request. How can I do it?

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Filippo De Bellis
  • 489
  • 1
  • 5
  • 9

2 Answers2

0

You can save Users by calling the service( using POST request) like in below sample.

var headers = new Headers();
headers.append('Content-Type', 'application/json');
this.http.post('http://www.syntaxsuccess.com/poc-post/', 
                       JSON.stringify({firstName:'Joe',lastName:'Smith'}),
                       {headers:headers})
.map((res: Response) => res.json())
.subscribe((res:Person) => this.postResponse = res);
Sundararaj Govindasamy
  • 8,180
  • 5
  • 44
  • 77
0

@Nitzan is correct in that there needs to be a servlet already running by the time you make the POST call.

I have been working on a project that involves an Angular2 front-end and a Java RESTful service for the back end. You can see how it is structured my answer to this question: how to integrate Angular 2 + Java Maven Web Application

For my project, I start the tomcat servlet (version 8.0.27) inside of netbeans, which also serves my app. This ensures that there is a server listening for specific requests made by the app, when the user gets to that point.

Code snippets

data.service.ts

Most of this .ts file came from the Angular Developer guide, credit goes to the author of that.

import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class DataService {
    constructor (private http: Http) {} // Inject Http client Service
    private baseListUrl: string = 'bar/request?id=';

    sendInput (input: string) {
        let uInput = JSON.stringify({input});
        let header = new Headers({'Content-Type': 'MIMETYPE/HERE'});
        let options = new RequestOptions({ headers: headers});

        this.http.post(this.baseListUrl.concat(input), uInput, options)
                        .map(this.extractData)
                        .catch(this.handleError);
    }

    private extractData(res: Response) {
        let body = res.json();
        // alert("body: " + body);
        return body.docs || {};
    }

    private handleError (error: any) {
        // In a real world app, we might use a remote logging infrastructure
        // We'd also dig deeper into the error to get a better message
        let errMsg = (error.message) ? error.message :
          error.status ? `${error.status} - ${error.statusText}` : 'Server error';
        console.error(errMsg); // log to console instead
        return Observable.throw(errMsg);
    }
}

foo.java

@Path("bar")
public class Baz{

    @POST
    @Path("/request")
    @Consumes(Mediatype.MIMETYPE_HERE)
    public Response doWhatYouNeed(string input) {
        // I don't have the exact code for you, but this should serve as a good starting point.
    }
}
Community
  • 1
  • 1
Scrambo
  • 579
  • 5
  • 17