1

I have an angular 7 app that is having an issue with calling a service twice.

I have multiple observables connected to a websocket. In the socket I am listening for different events to happen and performing appropriate actions.

app.module.ts

import { DataService } from './data.service';
....
providers: [
  DataService
],

one.component.ts

import { DataService } from './data.service';
....
constructor(private data: DataService) { }
....
ngOnInit() {
  this.data.receiveMessage().subscribe(msg => {
    this.msg = msg;
  });
}

two.component.ts

import { DataService } from './data.service';
....
constructor(private router: Router, private data: DataService) { }
ngOnInit() { }
....

data.service.ts

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import * as io from 'socket.io-client';

@Injectable()
export class DataService {
    receiveMessage() {
      return new Observable(observer => {
        this.socket.on('sendMessage', msg => {
          observer.next(msg);
        });
      });
    }
    ....
    other observables
 }

If I user Injectable provider root same thing happens.

I have other observables used in the app but it is only this one method that I am using in OnInit but taking it out causes the app to stop working.

user1020496
  • 99
  • 1
  • 9
  • You can use `rxJS shareReplay`. Check this [stackoverflow answer](https://stackoverflow.com/questions/51044291/using-sharereplay1-in-angular-still-invokes-http-request) – nitin9nair Jul 06 '19 at 05:36
  • 1
    Thanks for your suggestion. Turns out I had added in the app.component.html which was causing the entire app to render twice. Dumb mistake. – user1020496 Jul 06 '19 at 06:00

1 Answers1

0

Added in the app.component.html which was causing the entire app to render twice

user1020496
  • 99
  • 1
  • 9