0
votes

I have Angular Web application which I want to run as an Android app, using NativeScript.

For the websocket to work on Android, I'm using nativescript-websockets

tns plugin add nativescript-websockets

This works on the Android app.

require("nativescript-websockets");

this.websocket = new WebSocket("myUrl, "myProtocol");

I've added the above in a service which creates a websocket to the server.

But when I'm trying the run for web, I get the error:

Module not found: Error: Can't resolve 'nativescript-websockets'

When I remove require("nativescript-websockets"); from the service, it works for web.

What changes would I need such that it works for both Web and Mobile?

1

1 Answers

1
votes

You cannot use nativescript-websockets on the web part of your application. Since the nativescript-websockets package supports the browser based interface your solution could look pretty simple

  1. Create a base class of a service that is based on a general websockets interface. This could be a real or an abstract class - depends on your needs.
// services/price-provider.base.ts

export class PriceProviderBase {

    private socket: WebSocket;

    createSocket(): void {
        this.socket = new WebSocket('Your url here');
        this.socket.onopen = this.handleOpen.bind(this);
        this.socket.onclose = this.handleClose.bind(this);
        this.socket.onmessage = this.handleMessage.bind(this);
        this.socket.onerror = this.handleError.bind(this);
    }

    handleOpen() {
        // Do your stuff here...
    }
    ...
}
  1. Extend this base implementation as real services that will be used in web and nativescript environments

For web:

// services/price-provider.service.ts

import {Injectable} from '@angular/core';
import {PriceProviderBase} from '~/services/price-provider.base';

@Injectable({
    providedIn: 'root',
})
export class PriceProviderService extends PriceProviderBase {}

For nativescript:

// services/price-provider.service.tns.ts

import {Injectable} from '@angular/core';
import {PriceProviderBase} from '~/services/price-provider.base';

require('nativescript-websockets');

@Injectable({
    providedIn: 'root',
})
export class PriceProviderService extends PriceProviderBase {}

If the logic on web and nativescript apps is the same, the only difference in these two implementations will be require('nativescript-websockets'); line.