如何使用ionic2 native http插件发送HTTP PUT请求?

时间:2017-04-23 19:57:49

标签: rest cordova http ionic2 put

我正在尝试使用http native plugin从离子2应用发送HTTP put请求,但是,从文档中,我只看到postget请求方法已经实施。

首先:我想知道http方法deleteput是否未真正实现(因为我可能没有在文档中找到正确的位置)。

第二:如果没有实施,我们如何从离子2应用生成putdelete?是否可以在低级别执行此操作,而无需对插件本机/库代码进行修改?

提前致谢。

更新1:putdeletepostJSON实施(https://github.com/wymsee/cordova-HTTP/pull/105)的拉取请求,但是从2016年9月到现在2017年4月,它没有与主人合并。

更新2:首先,我要感谢@Jamil Hijjawi的回答。这解决了这个问题。但顺便说一句,我想提一下解决方案2需要一些服务器配置来绕过CORS,所以我选择了第一个。另外还有一篇很好的文章https://www.joshmorony.com/using-cordova-plugins-in-ionic-2-with-ionic-native/解释了如何使用不属于“Ionic Native”的cordova插件,我建议你仔细阅读。我想指出一个部分,如:

  

在Ionic 2中使用非Ionic Native插件的方式与在任何Cordova项目中使用它的方式相同,但是插件的文档说你应该使用它。但是,您需要执行一些额外的步骤,因为TypeScript会导致一些问题。

进一步说明我们需要在cordovaHTTP之类的地方通过插件声明全局导出的变量declarations.d.ts,因此打字稿知道这一点。声明后,不需要依赖注入。以下是我在随机组件函数中使用的代码段。

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  constructor(
    public navCtrl: NavController,
    private _platform: Platform
  ) {
    this._platform.ready().then(() => {

      // ========== We need this part
      cordovaHTTP.put('http://192.168.0.5:8081/test-route', {
        really: "Yea!"
      }, {}, (res: any) => {
        console.log(res);
      }, (err: any) => {
        console.log(err);
      });
      // ========== till here, as for the example of usage
    });
  }

}

1 个答案:

答案 0 :(得分:2)

选项1:

cordova-http插件仅支持GETPOST,因此如果您想使用PUT直接从发出请求请求的作者ionic plugin add https://github.com/spuentesp/cordova-HTTP安装插件3}}使用此命令ionic-native

但是cordovaHTTP没有为这些API实现声明,因此您可以在declarations.d.ts中声明Http命名空间并使用您想要的API

选项2:

在角度

中使用this.http.put(url, JSON.stringify(hero), {headers: headers}).map(res => res.json()); 服务
if (!Ar[x, y + 1].HasBeenVisited && y + 1 <= (Width / TileWidth))
            return true;

Http class doc https://github.com/spuentesp/cordova-HTTP