0

我正在使用这个种子项目处理 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 for URL:null

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

4

2 回答 2

-1

you can use nativescript http with angular , following example:

first import http serves in the top of the service component

var http = require("http");

in the sevice.ts file ,you need to convert the http promise to 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 
                } );
    }

then you can subscribe to the observeable as you used befor,

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

Note : now you can remove the import statment of angular http since its not needed

于 2017-03-12T18:36:05.847 回答
-1

您需要使用 NativeScript HTTP 模块,这里是文档。不同的移动平台与常规浏览器的工作方式不同,因此您需要一个 {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");

于 2016-08-01T22:35:45.077 回答