Natviescript Angular2 HTTP

时间:2016-07-31 03:18:52

标签: angular nativescript angular2-nativescript

我正在使用此种子项目处理angular2 + nativescript项目,我无法使用此代码进行简单的HTTP POST调用

return this.http.post(`${AppConfigService.API_PATH}/login`, body, options)
          .map(res => res.json())
          .catch((err: any) => {
            return Observable.throw(err);
          });

此代码在普通angular2应用程序中运行正常,但在本机脚本中它会给出错误: 响应状态:200表示URL:null

我还在Github上记录了这个问题:https://github.com/NativeScript/NativeScript/issues/2536

2 个答案:

答案 0 :(得分:-1)

您需要使用NativeScript HTTP模块,here是文档。不同的移动平台与常规浏览器的工作方式不同,因此您需要一个{N}核心模块来管理不同的平台特定API。 JSON POST看起来像这样:

var result;

http.request({
    url: "https://httpbin.org/post",
    method: "POST",
    headers: { "Content-Type": "application/json" },
    content: JSON.stringify({ MyVariableOne: "ValueOne", MyVariableTwo: "ValueTwo" })
}).then(function (response) {
    // result = response.content.toJSON();
    // console.log(result);
}, function (e) {
    // console.log("Error occurred " + e);
});

您必须确保使用var http = require("http");

答案 1 :(得分:-1)

你可以使用带有角度的nativescript http,例如:

首先导入http服务在服务组件的顶部

var http = require("http");
在sevice.ts文件中

,您需要将http promise转换为observable。

//GET Example
    getList(): Observable<News[]> {
        return Observable.fromPromise(
                    http.getJSON(serverConfig.apiUrl+"news")
                ).map(function(res:any) {
                    console.log('finished sendign request'); 
                    return res as News[] 
                } );

    }


//POST EXAMPLE

submitFormData(data): Observable<Forms> {
        let url:string=serverConfig.apiUrl+"forms/";
        let headers:any = { 'Content-Type': 'application/json', 'Authorization': 'Bearer '+this.appSettings.getString("access_token")};
        let req:any={
            url:url,
            method: "post",
            headers:headers,
            content: JSON.stringify(data)
        };

        return Observable.fromPromise(
                    http.getJSON(req)
                ).map(function(res:any) {
                    return res as Forms 
                } );
    }

然后你可以订阅你所使用的观察对象,

this.newsService.getList().subscribe((res) => {
    this.news= res;
});

注意:现在您可以删除角度http的导入语句,因为它不需要