Android 如何在本机后台服务中使用(角度)HTTP客户端-NativeScript

Android 如何在本机后台服务中使用(角度)HTTP客户端-NativeScript,android,angular,typescript,nativescript,Android,Angular,Typescript,Nativescript,如何在我的后台服务android中使用angular http客户端 我的应用程序需要将数据从后台服务发送到我的服务器 我正在使用NativeScript/Angular 我的后台服务 declare var android; if (application.android) { (<any>android.app.Service).extend("org.tinus.Example.BackgroundService", { onStartCommand:

如何在我的后台服务android中使用angular http客户端

我的应用程序需要将数据从后台服务发送到我的服务器

我正在使用NativeScript/Angular

我的后台服务

declare var android;

if (application.android) {
    (<any>android.app.Service).extend("org.tinus.Example.BackgroundService", {
        onStartCommand: function (intent, flags, startId) {
            this.super.onStartCommand(intent, flags, startId);
            return android.app.Service.START_STICKY;
        },
        onCreate: function () {
            let that = this;

            geolocation.enableLocationRequest().then(function () {
                that.id = geolocation.watchLocation(
                    function (loc) {

                        if (loc) {
                            // should send to server from here

                        }
                    },
                    function (e) {
                        console.log("Background watchLocation error: " + (e.message || e));
                    },
                    {
                        desiredAccuracy: Accuracy.high,
                        updateDistance: 5,
                        updateTime: 5000,
                        minimumUpdateTime: 100
                    });
            }, function (e) {
                console.log("Background enableLocationRequest error: " + (e.message || e));
            });
        },
        onBind: function (intent) {
            console.log("on Bind Services");
        },
        onUnbind: function (intent) {
            console.log('UnBind Service');
        },
        onDestroy: function () {
            geolocation.clearWatch(this.id);
        }
    });
}
为1发行

System.err: TypeError: Cannot read property 'post' of undefined
二,。使用本机代码

     let url = new java.net.URL("site/fsc");
     let connection = null;
     try {
          connection = url.openConnection();
     } catch (error) {
           console.log(error);
     }

     connection.setRequestMethod("POST");
     let out = new java.io.BufferedOutputStream(connection.getOutputStream());
     let writer = new java.io.BufferedWriter(new java.io.OutputStreamWriter(out, "UTF-8"));
     let data = 'mutation NewDriverLoc{saveDriverLocation(email:"' + (<SystemUser>JSON.parse(getString('User'))).email + '",appInstanceId:' + (<ApplicationInstance>JSON.parse(getString('appInstance'))).id + ',geoLocation:{latitude:' + loc.latitude + ',longitude:' + loc.longitude + ',accuracy:' + loc.horizontalAccuracy + '}){id}}';
     writer.write(data);
     writer.flush();
     writer.close();
     out.close();
     connection.connect();
所以基本上第一种方法是有角度的,问题是我没有注入所有需要的服务/不确定如何注入

第二种方法是本机的,问题是网络在主线程上。我需要使用AsyncTask,只是不确定如何尝试使用,但请记住使用NativeScriptHttpClientModule。我还没有试过,所以我不能说它会起作用

我最后用的是这个。不使用服务有点黑客行为,但它是有效的

编辑日期:2019年6月 在下面的示例中,我使用的是不推荐使用的@angular/http包中的BrowserXhr。我已经更新为使用私有AngularAPI。该示例已更新

编辑日期:2019年4月 因此,我最终确实需要它,并设法将HttpClient注入到一个非角度应用程序中。这也适用于后台服务和工作人员

import { HttpBackend, HttpClient, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HTTP_INTERCEPTORS, XhrFactory, ɵangular_packages_common_http_http_d as BrowserXhr, ɵHttpInterceptingHandler } from "@angular/common/http";
import { Injector } from '@angular/core';
import { NSFileSystem } from "nativescript-angular/file-system/ns-file-system";
import { NsHttpBackEnd } from "nativescript-angular/http-client/ns-http-backend";
import { Observable } from 'rxjs';

export class TestInterceptor implements HttpInterceptor {
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        console.log("intercepted", req);
        return next.handle(req);
    }


}

const httpClientInjector = Injector.create([
    {
        provide: HttpClient, useClass: HttpClient, deps: [
            HttpHandler
        ]
    },
    { provide: HttpHandler, useClass: ɵHttpInterceptingHandler, deps: [HttpBackend, Injector] },
    { provide: HTTP_INTERCEPTORS, useClass: TestInterceptor, multi: true, deps: [] }, // remove or copy this line to remove/add more interceptors
    { provide: HttpBackend, useExisting: NsHttpBackEnd },
    { provide: NsHttpBackEnd, useClass: NsHttpBackEnd, deps: [XhrFactory, NSFileSystem] },
    { provide: XhrFactory, useExisting: BrowserXhr },
    { provide: BrowserXhr, useClass: BrowserXhr, deps: [] },
    { provide: NSFileSystem, useClass: NSFileSystem, deps: [] }
]);

export const httpClient = httpClientInjector.get(HttpClient);
您可以在Injector之后添加到阵列的顶部。创建[以下内容:

{provide:MyService,useClass:MyService,deps:[HttpClient]}请记住,deps必须按照构造函数要求的顺序

然后,通过调用const myService=httpClientInjector.getMyService;

您可以尝试使用,但请记住使用NativeScriptHttpClientModule。我还没有尝试过,所以我不能说它会起作用

我最后使用的是。不使用服务有点黑客,但它可以工作

编辑日期:2019年6月 在下面的示例中,我使用的是不推荐使用的@angular/http包中的BrowserXhr。我已更新为使用私有angular API。该示例已更新

编辑日期:2019年4月 因此,我最终确实需要它,并设法将HttpClient注入到一个非角度应用程序中。这也应该适用于后台服务和工作人员

import { HttpBackend, HttpClient, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HTTP_INTERCEPTORS, XhrFactory, ɵangular_packages_common_http_http_d as BrowserXhr, ɵHttpInterceptingHandler } from "@angular/common/http";
import { Injector } from '@angular/core';
import { NSFileSystem } from "nativescript-angular/file-system/ns-file-system";
import { NsHttpBackEnd } from "nativescript-angular/http-client/ns-http-backend";
import { Observable } from 'rxjs';

export class TestInterceptor implements HttpInterceptor {
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        console.log("intercepted", req);
        return next.handle(req);
    }


}

const httpClientInjector = Injector.create([
    {
        provide: HttpClient, useClass: HttpClient, deps: [
            HttpHandler
        ]
    },
    { provide: HttpHandler, useClass: ɵHttpInterceptingHandler, deps: [HttpBackend, Injector] },
    { provide: HTTP_INTERCEPTORS, useClass: TestInterceptor, multi: true, deps: [] }, // remove or copy this line to remove/add more interceptors
    { provide: HttpBackend, useExisting: NsHttpBackEnd },
    { provide: NsHttpBackEnd, useClass: NsHttpBackEnd, deps: [XhrFactory, NSFileSystem] },
    { provide: XhrFactory, useExisting: BrowserXhr },
    { provide: BrowserXhr, useClass: BrowserXhr, deps: [] },
    { provide: NSFileSystem, useClass: NSFileSystem, deps: [] }
]);

export const httpClient = httpClientInjector.get(HttpClient);
您可以在Injector之后添加到阵列的顶部。创建[以下内容:

{provide:MyService,useClass:MyService,deps:[HttpClient]}请记住,deps必须按照构造函数要求的顺序

然后,您可以通过调用const myService=httpClientInjector.getMyService;来获得服务。请查看此链接

如选项2所述,将以下内容添加到本机代码中,应该可以正常工作

let policy = new 
android.os.StrictMode.ThreadPolicy.Buiilder().permitAll().build();
andriod.os.StrictMode.setThreadPolicy(policy);
请看这个链接

如选项2所述,将以下内容添加到本机代码中,应该可以正常工作

let policy = new 
android.os.StrictMode.ThreadPolicy.Buiilder().permitAll().build();
andriod.os.StrictMode.setThreadPolicy(policy);

这是可行的,但在主线程上使用套接字让人感觉不舒服。这是可行的,但在主线程上使用套接字让人感觉不舒服thread@TinusJackson我已经更新了我的响应。这样,您应该能够使用Nativescript的HttpClient。我设法在一个空白应用程序上使用HttpClient,而不是在一个角度上使用纯TSapplication@TinusJackson我已经更新了我的回复。通过这种方式,您应该能够使用Nativescript的HttpClient。我设法在空白应用程序上使用HttpClient,而不是在角度应用程序中使用纯TS
let policy = new 
android.os.StrictMode.ThreadPolicy.Buiilder().permitAll().build();
andriod.os.StrictMode.setThreadPolicy(policy);