Angular2、Ionic2 post 到网络服务

Angular2, Ionic2 post to web service

import {Page, Platform} from 'ionic-angular';
import { Http, Headers, Response, RequestOptions, HTTP_PROVIDERS} from 'angular2/http';
import { bootstrap } from 'angular2/platform/browser';
import { Component, Injectable, Inject } from 'angular2/core';
import 'rxjs/Rx';
import { CORE_DIRECTIVES, FORM_DIRECTIVES } from 'angular2/common';
import {Observable}     from 'rxjs/Observable';

@Page({
directives: [ CORE_DIRECTIVES, FORM_DIRECTIVES ],  
templateUrl: 'build/pages/getting-started/getting-started.html'
})

@Injectable()
export class GettingStartedPage {
    public platform;
    public networkState;
    private headers;
    private _apiUrl = 'http://172.16.2.115:3004/message'; 
    subject: string;
    message: string;
    comments: string;

    constructor(platform: Platform, public http: Http) {
        this.platform = platform;
        this.headers = new Headers();
        this.headers.append('Content-Type', 'application/x-www-form-urlencoded');
    }

    onSubmit(value) {
        this.send(value.subject, value.body);
    }

    send(subject, body)
    {
        var message = "subject=" + subject + "&body=" + body;

        let result = this.http.post(this._apiUrl,
            body, 
            {
                headers: this.headers
            }).map(res => {
                this.comments = res.json();
                });              

        this.send(subject, body).subscribe(res => {
            console.log(message);
            console.log(this._apiUrl);
        });

        return result;       
    }
}

我正在尝试使用 Ionic2 和 Angular2 创建移动应用程序 beta.This 应用程序将使用 POST 向 Rails 网络服务发送电子邮件。 Rails 网络服务工作正常。我似乎没有开始使用移动应用程序。

有误会

   this.send(subject, body).subscribe(res => {
        console.log(message);
        console.log(this._apiUrl);
    });

将采用不同的方法

onSubmit(value) {
    this.send(value.subject, value.body)
    .subscribe(res => {
        console.log(message);
        console.log(this._apiUrl);
    });
}

send(subject, body)
{
    var message = "subject=" + subject + "&body=" + body;

    return this.http.post(this._apiUrl,
        body, 
        {
            headers: this.headers
        }).map(res => {
            this.comments = res.json();
        });              

}

你应该这样重构你的代码:

onSubmit(value) {
    this.send(value.subject, value.body).subscribe(res => {
        console.log(message);
        console.log(this._apiUrl);
    });

}

send(subject, body)
{
    var message = "subject=" + subject + "&body=" + body;

    let result = this.http.post(this._apiUrl,
        body, 
        {
            headers: this.headers
        }).map(res => {
            this.comments = res.json();
        });              

    return result;       
}