【问题标题】:How to make POST request to server in ionic2如何在ionic2中向服务器发出POST请求
【发布时间】:2017-04-28 23:10:50
【问题描述】:

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

请建议我如何发送请求?

提前致谢

【问题讨论】:

标签: cordova angular ionic2


【解决方案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);
  });
}

【讨论】:

  • 我尝试添加以下行,构造函数(公共 http: Http)它给出的错误是 [ts] 找不到 Http..
  • 你用过 import { Http, Headers, RequestOptions } from '@angular/http'; ?
  • this.http.post(url, JSON.stringify(dataBody), headers).subscribe(data => { console.log(data); });上面的代码我用来发送发布请求,但是数据在 url 中......它应该在请求的正文中。
【解决方案2】:

声明 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());
    }
}

在打字稿中使用

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

【讨论】:

    猜你喜欢
    • 2020-09-11
    • 1970-01-01
    • 1970-01-01
    • 2019-05-30
    • 1970-01-01
    • 1970-01-01
    • 2016-01-04
    • 2013-09-02
    • 1970-01-01
    相关资源
    最近更新 更多