Search code examples
angularangular-services

Communication between 2 components through service doesn't working


I need help with this. I want send a variable from component to another component via shared service. I have got inspired by this solution, but in the receiver component the "nevim" value is still undefined and I don't know why. Thanks a lot.

Edit: Ok, I discovered the problem, it was that the Sender and Receiver component were not using the same instance of service.

So if you try this in your own project it should be working.

Service:

customNevim$: Observable<string>;
private customNevimSubject = new Subject<string>();

constructor() {
    this.customNevim$ = this.customNevimSubject.asObservable();
}

customNevim(data) {
    this.customNevimSubject.next(data);
}

Sender Component:

 message2: string = "test";

 public constructor( private myService: MyService) {
     this.myService.customNevim(this.message2);
 }

Reciever component:

nevim: string;

public constructor( private myService: MyService) {
    this.myService.customNevim$.subscribe((data) => {
                    this.nevim = data; 
                    //after I try console.log "this.nevim" it still shows it as undefined
                }
}

Solution

  • Try this.. Change

    this.customNevim$ = this.customNevimSubject.asObservable();
    

    to nothing in constructor and your observable should be

    Non rxjs6 --> this.customNevim$ = Observable.from(this.customNevimSubject); import "rxjs/add/observable/from";

    Rxjs6 -->this.customNevim$ = from(this.customNevimSubject);

    Rrxjs6 --> import from import { from } from 'rxjs';

    Updating your example...

    Service

    private customNevimSubject = new BehaviourSubject<string>("TestBehaviour");
    customNevim$: Observable<string> = Observable.from(this.customNevimSubject);
    
    constructor(){}
    
    customNevim(data) {
      this.customNevimSubject.next(data);
    }
    

    Sender Component

     message2: string = "test";
    
     constructor(private myService: MyService){}
    
     ngOnInit(){
       this.myService.customNevim(this.message2);
     }
    

    Reciever Component

    nevim: string;
    
    constructor(private myService: MyService){}
    
    ngOninit(){
           this.myService.customNevim$.subscribe((data) => {
             /// Log the data
             console.log(data);
           }
    }