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?

3
  • 1
    You need to have a container running your servlet and then make a http request (probably POST) to the url of that servlet. Commented Jul 28, 2016 at 9:09
  • Angular2 HTTP Client Commented Jul 28, 2016 at 9:12
  • I use eclipse neon with apache tomcat server v9.0 Commented Jul 28, 2016 at 9:20

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

Comments

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.
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.