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

时间:2018-06-18 06:59:45

标签: android angular typescript nativescript

如何在后台服务(android)中使用角度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)。使用Injector注入我的服务

         const injector = Injector.create([ { provide: ExampleService, useClass: ExampleService, deps: [HttpClient] }]);
         const service = injector.get(ExampleService);
         console.log(service.saveDriverLocation); // This prints
         service.saveDriverLocation(new GeoLocation(loc.latitude, loc.longitude, loc.horizontalAccuracy, loc.altitude), ['id']); // This complains 

(1)的问题

System.err: TypeError: Cannot read property 'post' of undefined

(2)。使用本机代码

     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();

(2)

的问题
System.err: Caused by: android.os.NetworkOnMainThreadException

所以基本上第一种方法是角度,问题是我不会注入所有需要的服务/不确定如何。

第二种方法是原生的,问题是网络在主线程上。我需要使用AsyncTask而不确定如何

2 个答案:

答案 0 :(得分:3)

请看这个链接 How do I fix android.os.NetworkOnMainThreadException?

将以下内容添加到您在本机代码中,就像您在选项2中提到的那样。它应该可以正常工作

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

答案 1 :(得分:0)

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

我最终使用的是non-angular Http module。不使用服务有点蠢,但它确实有用。

编辑(2019年4月)

所以我最终真的需要这个,并设法在非角度应用程序中注入HttpClient。这也适用于后台服务和工作人员。

import { HttpBackend, HttpClient, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HTTP_INTERCEPTORS, ɵHttpInterceptingHandler } from "@angular/common/http";
import { Injector } from '@angular/core';
import { BrowserXhr } from '@angular/http';
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,
            BrowserXhr
        ]
    },
    { 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: [BrowserXhr, NSFileSystem] },
    { provide: BrowserXhr, useClass: BrowserXhr, deps: [] },
    { provide: NSFileSystem, useClass: NSFileSystem, deps: [] }
]);

export const httpClient = httpClientInjector.get(HttpClient)

请注意,我也在利用拦截器。

此实现缺少HttpClientXsrfModule,因此如果您打算使用它,您必须自己添加它。也就是说,目前似乎不支持XHR cookie:https://github.com/NativeScript/NativeScript/issues/2424

如果您想使用以下服务:

export class MyService {
    constructor(private http: HttpClient) { }
}

您可以将以下内容添加到数组顶部(Injector.create[之后):

{ provide: MyService, useClass: MyService, deps: [HttpClient] }(记住deps必须符合构造函数所需的顺序!)

然后,您可以致电const myService = httpClientInjector.get(MyService);

来获取服务