【问题标题】:Angular2 typescript POST requestAngular2打字稿POST请求
【发布时间】:2016-12-02 13:44:52
【问题描述】:

我正在测试这个样本:http://plnkr.co/edit/WTu5G9db3p4pKzs0WvW6?p=preview

此代码实现了一个包含姓名、邮件、个人资料的登录表单。单击提交按钮后,屏幕上会出现一条警报,其中包含名称和电子邮件字段。

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

在上面,app.component.ts 中的 saveUser 函数。它在单击按钮时执行警报。在 saveUser 函数上,我想调用一个 POST 请求。我该怎么做?

【问题讨论】:

  • 您需要有一个容器运行您的 servlet,然后向该 servlet 的 url 发出 http 请求(可能是 POST)。
  • 我使用 eclipse neon 和 apache tomcat server v9.0

标签: angular typescript http-post


【解决方案1】:

您可以通过调用服务(使用POST 请求)来保存用户,如下面的示例

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

【讨论】:

    【解决方案2】:

    @Nitzan 是正确的,因为在您进行 POST 调用时需要有一个 servlet 已经在运行。

    我一直在从事一个涉及 Angular2 前端和后端 Java RESTful 服务的项目。你可以看看我对这个问题的回答是如何构成的:how to integrate Angular 2 + Java Maven Web Application

    对于我的项目,我在 netbeans 中启动了 tomcat servlet(版本 8.0.27),它也为我的应用程序提供服务。这可确保当用户到达该点时,有一个服务器正在侦听应用程序发出的特定请求。

    代码 sn-ps

    data.service.ts

    这个 .ts 文件的大部分来自 Angular Developer guide,归功于该文件的作者。

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

    【讨论】:

      猜你喜欢
      • 2017-03-10
      • 1970-01-01
      • 1970-01-01
      • 2016-05-14
      • 2017-03-12
      • 1970-01-01
      • 2017-12-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多