Angular 5 and atmosphere.js

1.2k Views Asked by At

I need to use atmosphere.js in my angular 5 project.

I've done these steps:

npm install --save @types/atmosphere.js
npm install --save atmosphere.js

and I've created a service:

import { Injectable } from '@angular/core';
import * as Rx from 'rxjs';
import * as Atmosphere from 'atmosphere.js';
import {Subject} from 'rxjs/Subject';
@Injectable()
export class  WebsocketService {
  public eventsSubject: Rx.Subject<any> = new Rx.Subject<any>();
  private url:string = "http://localhost:4200/ws/register";

  private socket: Atmosphere.Atmosphere;
  private subSocket: any;
  private request: Atmosphere.Request;

  public dataStream: Subject<any> = new Subject<any>();

  constructor() {

     ...

     try {
        this.subSocket = this.socket.subscribe(this.request);
     } catch (e) {
        console.log("Error: " + e);
     }
  }

but the socket is always undefined.

where is my error?

thanks

1

There are 1 best solutions below

0
On BEST ANSWER

You should actually instantiate your socket in someway, my guess is using new:

private socket: Atmosphere.Atmosphere = new Atmosphere.Atmosphere();

The first part is just a type definition you give to the TypeScript compiler. The property will stay undefined until you actually assign something to it.

Although looking over their api, this does not seem to be the right way. Try this:

export class  WebsocketService {
  // ...
  private socket: typeof Atmosphere = Atmosphere;
  private subSocket: Subscription;
  private request: Atmosphere.Request = new atmosphere.AtmosphereRequest();

  constructor() {
     try {
        this.subSocket = this.socket.subscribe(this.request);
     } catch (e) {
        console.log("Error: " + e);
     }
  }
}