简体   繁体   中英

Angular 4 calling Component from Service using Observable and Subscribe

I have a service calling a component via Observable and Subscribe but for the life of me I can not see any results from my component. My code is as follows. The service and the Component is registered in my app.module.ts.

 @Injectable()
 export class MyService {

  private messageSource = new Subject<any>();
  currentMessage = this.messageSource.asObservable();

  constructor() {}

  doSomething() {
   this.messageSource.next();
   console.log(" doSomething .........");
  }
}

@Component({
  selector: 'angular-loader',
  templateUrl: './loader.component.html',
  styleUrls: ['./loader.component.css'],
})

export class MyComponent implements OnInit {

   private subscription: Subscription;
   message:string;

   constructor(private myService: MyService) { }

   ngOnInit() {
     this.myService.currentMessage.subscribe(() => {
     alert('(Component2) Method called!');
    });
   }
 }

It can depend on your RxJS version, but afaik you can use subject.next() with no value.

To me there are two possibilities :

  • Either your RxJS version is too low and the next() without value doesn't do anything (I don't think that's the issue here).
  • Or there is an issue with the way your components are doing the communication. It could be because you call the doSomething() method from another component and the one that should subscribe() isn't loaded correctly and therefore cannot receive the result, in which case I advise you should check if your components are loaded correctly, and I'd also move the subscription from the ngOnInit() to the constructor() .

What is putting something into your messageSource ?

I'm used to seeing something that looks more like this:

  doSomething(message: string) {
   this.messageSource.next(message);
   console.log(" doSomething .........");
  }

This then adds the message onto the Observable stream which will then be broadcast to your subscribers.

(But even if it is not passed a value, it should still be broadcasting a notification and you should be seeing your alert.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM