Angular-cli: New CLI app doesn't register service worker if socket.io-client is used

Created on 5 Jan 2018  路  5Comments  路  Source: angular/angular-cli

Versions

@angular/cli: 1.6.3
node: 8.9.3
npm: 5.5.1

Repro steps

  • Step 1: Initialize new CLI app (ng new ngsw-test --service-worker)
  • Step 2: npm install socket.io-client --save and npm install "@types/socket.io-client" --save-dev
  • Step 3: In the default component, initialize a new socket:
import { Component } from '@angular/core';
import * as socket from 'socket.io-client';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
  private socket: SocketIOClient.Socket;

  constructor() {
      //Comment this out and the service worker gets registered fine
      this.socket = socket('//localhost:8081', {
        path: '/ws'
      });
  }
}

Observed behavior

The new CLI app doesn't register the service worker (if the socket initialization in app.component.ts is commented out it works fine). No errors in the console (other than connection refused if the socket server isn't running. I get the same behavior if it connects fine though).

Desired behavior

Register the service worker even when a socket is being used.

Mention any other details that might be useful (optional)

investigation

Most helpful comment

I found this workaround:
```
constructor(private ngZone: NgZone) {

this.ngZone.runOutsideAngular(() => {

  this.io = io(yourUrl);
});

}

All 5 comments

An update to this: it works fine if I initialize the socket with autoConnect false like so:

this.socket = socket('[url]', { autoConnect: false });

Even if I setTimeout for several seconds before trying to connect, it appears to wait for the socket to be initialized and then subsequently doesn't load ngsw-worker.js. The only way I can get the service worker to stay is if I connect to the socket on a UI action (like a button press).

maybe this is related to angular #20970, the zone does not get stable because the autoConnect of socket.io is doing a setInterval (check connection, reconnect if broken)?

I found this workaround:
```
constructor(private ngZone: NgZone) {

this.ngZone.runOutsideAngular(() => {

  this.io = io(yourUrl);
});

}

I think this is the same as https://github.com/angular/angular-cli/issues/9021. If this is still a problem can you follow up there please?

This issue has been automatically locked due to inactivity.
Please file a new issue if you are encountering a similar or related problem.

Read more about our automatic conversation locking policy.

_This action has been performed automatically by a bot._

Was this page helpful?
0 / 5 - 0 ratings