1

I am following this tutorial. works fine receiving message with App-component but does not work for another components . I am using MessageService as a entire application scope in @ngModule for injection . Appcomponent receives message, but other components can send msgs does not receive message.

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { Subject } from 'rxjs/Subject';

    @Injectable()
    export class MessageService {
        private subject = new Subject<any>();

        sendMessage(message: string) {
            this.subject.next({ text: message });
            console.log('called:' + message);
        }
        clearMessage() {
            this.subject.next();
        }
        getMessage(): Observable<any> {
          console.log('message geting');
            return this.subject.asObservable();
        }

    }

2)LoginComponent //for sending message

import { Observable } from 'rxjs/Observable';
import { MessageService } from '../services/message.service';


@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {


    constructor(
    private messageservice ?:MessageService
    ) { 

  sendMessage(): void {
    console.log("send");
    this.messageservice.sendMessage('Message from waqas to login');
    }
clearMessage(): void {
    // clear message
    this.messageservice.clearMessage();
}

3)TestComponent //testing for receiving message

    import { Component, OnInit, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs';
import { MessageService } from '../services/index';

@Component({
  selector: 'app-test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.css'],

})
export class TestComponent implements OnDestroy  {
  ngOnDestroy(): void {
this.subscription.unsubscribe();
  }
 // title = 'app';
 message: any;
 subscription: Subscription;

 constructor(private messageService: MessageService) {
     // subscribe to home component messages
    this.subscription = this.messageService.getMessage().subscribe(message => { this.message = message;console.log(message) });
    // console.log('receving'+this.message);

   }
  }

AppModule File

providers: [MessageService,UserService,AuthenticationService,UploadFileService,CategoryService,ProductService,AuthGuard,AdminAuthGuard,

    {provide: ErrorHandler, useClass: AppErrorHandler},
    {
      provide: HTTP_INTERCEPTORS,
      useClass: TokenInterceptor,
      multi: true
    }
    ],
  bootstrap: [AppComponent],
 })

I do not know how to change bootstrap provider for TestComponent or LoginComponent to use MessageService . I googled and other questions over stackoverflow too but could not solve my problem .

Thanks in advance

naila naseem
  • 577
  • 3
  • 12
  • 21

1 Answers1

0

I think that your problem is a conceptual one. You are expecting to be able to effectively send a message from the LoginComponent to the TestComponent via the MessageService.

However, since, apparently, you are using both of those components as top-level (routable) components, and neither has the other in it's view hierarchy, only one of them ever exists at the same point in time.

So, when your LoginComponent sends it message, the TestComponent is not there to receive it - it subscribes to the MessageService after the MessageService has already emitted the message.

One possible fix is to make the MessageService's Observable a BehaviorSubject instead of a Subject.

The difference is that a BehaviorSubject will always emit the last message on subscription. This may or may not be suitable for your use case.

GreyBeardedGeek
  • 29,460
  • 2
  • 47
  • 67