如何在ionic2中向服务器发出POST请求

时间:2016-12-12 12:21:19

标签: cordova angular ionic2

我在angular2工作,我想向服务器发送POST请求。

请建议我如何发送请求?

提前致谢

2 个答案:

答案 0 :(得分:1)

使用的实际代码可以是:

import { Http, Headers, RequestOptions } from '@angular/http';

......

constructor(public http: Http) { }

sendPushNotification(deviceId: string) {
  let url = 'https://fcm.googleapis.com/fcm/send';
  let body = 
   {
     "notification": {
         "title": "Notification title",
         "body": "Notification body",
         "sound": "default",
         "click_action": "FCM_PLUGIN_ACTIVITY",
         "icon": "fcm_push_icon"
     },
     "data": {
         "hello": "This is a Firebase Cloud Messagin  hbhj g Device Gr new v Message!",
     },
     "to": "device token"
   };
let headers: Headers = new Headers({
  'Content-Type': 'application/json',
  'Authorization': 'key='+this.someKey
});
let options = new RequestOptions({ headers: headers });

console.log(JSON.stringify(headers));

  this.http.post(url, body, headers).map(response => {
    return response;
  }).subscribe(data => {
     //post doesn't fire if it doesn't get subscribed to
     console.log(data);
  });
}

答案 1 :(得分:0)

声明ApiService以发布到api

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';


@Injectable()
export class ApiService {

    constructor(private http: Http) {
        console.log('ApiService init');
    }

    postSample() {
        let param = { val1:'test'};
        return this.http.post('http://sample.com',
            param
        ).map(res => res.json());
    }
}

在typeScript中使用

this.ApiService.postSample().subscribe(data => {
      console.log(data);
    });