代码之家  ›  专栏  ›  技术社区  ›  Tinus Jackson

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

  •  1
  • Tinus Jackson  · 技术社区  · 8 年前

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

    我正在使用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);
            }
        });
    }
    

    我试过两种方法。

             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
    

    (二)。使用本机代码

         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 回复  |  直到 7 年前
        1
  •  3
  •   Rikus    8 年前

    How do I fix android.os.NetworkOnMainThreadException?

    将以下内容添加到您的本机代码中,就像您在选项2中提到的那样。它应该是有效的

    let policy = new 
    android.os.StrictMode.ThreadPolicy.Buiilder().permitAll().build();
    andriod.os.StrictMode.setThreadPolicy(policy);
    
        2
  •  1
  •   Eduardo Speroni    7 年前

    ReflectiveInjector

    我最后使用的是 non-angular Http module

    BrowserXhr @angular/http

    编辑(2019年4月)

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

    缺少此实现 HttpClientXsrfModule https://github.com/NativeScript/NativeScript/issues/2424

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

    Injector.create[ )以下内容:

    { provide: MyService, useClass: MyService, deps: [HttpClient] }

    const myService = httpClientInjector.get(MyService);

    推荐文章