0

Here is service:

@Injectable() 
export class AuthService {

  public reset: Subject<any>;

  constructor() {
    this.reset = new Subject();
  }

  public logout() {
   this.reset.next('logout');
  }
}

This is another service which wants to know when logout() happens:

@Injectable()
export class StoreService() {

  constructor(private auth: AuthService) {

    this.auth.changes.subscribe((value) => {
      // Do not work God knows why
    });
  }
}

Subscription in the second service will never get any events. Why?

3 Answers3

3

I found the problem - there were multiple instances of AuthService (Thank you @Martin). The problem is if somebody adds provide: [AnyService] to any component, there will be no errors but you will get two (or more) instances of service. This kind of bug can be easily found by add console.log(counter++) to service constructor.

1
@Injectable() 
export class AuthService {

  public reset: Subject<any>;
  reset$ = null;

  constructor() {
    this.reset = new Subject();
    this.reset$ = this.reset.asObservable();
  }

  public logout() {
   this.reset.next('logout');
  }
}

And other service consuming it subscribe to the event.

@Injectable()
export class StoreService() {

  constructor(private auth: AuthService) {

    this.auth.reset$.subscribe((value) => {
      console.log(value);
      //implement your own logic here
    });
  }
}
Sefa
  • 8,373
  • 9
  • 48
  • 77
0

You have to define Observable string to which you can subscribe in another service or component :

@Injectable() 
export class AuthService {

  public reset: Subject<any>;
  /**
   * Observable string streams
   */
  notifyObservable$ = this.reset.asObservable();


  constructor() {
    this.reset = new Subject();
  }

  public logout() {
   this.reset.next('logout');
  }
}

// StorageService

@Injectable()
export class StoreService() {

  constructor(private auth: AuthService) {

    this.auth.notifyObservable$.subscribe((value) => {
      // Do not work God knows why
    });
  }
}
ranakrunal9
  • 12,722
  • 2
  • 38
  • 43
  • Thank you for your answer, but Subject already returns Observable, why I have to call asObservable() on Observable? Anyway, it still not working – Андрей Куценко Oct 11 '16 at 12:52
  • you can check answer http://stackoverflow.com/questions/39738974/can-i-emmit-the-event-from-parent-to-child-in-angular2/39739184#39739184 for your reference – ranakrunal9 Oct 11 '16 at 12:58
  • Communication between service and component or between two components through service works excellent but it's not my case. I faced with the situation when one service doesn't get any events from another one. And it doesn't matter what kind of event emitter I use - it can be EventEmitter class or Subject, still not working ( – Андрей Куценко Oct 11 '16 at 13:04