dizzydizzy
dizzydizzy

Reputation: 157

Pass data from component to service via observables

I need to send info from component A, to Service, work it there, and then send it to component B. A and B are siblings. I need component A to trigger this, to get a desired result on component B.

Im trying to use an observable with rxjs to achieve this (I dont know if that's the best way or practice to do so)

Currently my component A look like this:

import { Observable } from "rxjs/Rx"
import { of, Subscription } from 'rxjs';
import { SoporteService    } from '../soporte/services/soporte.service';

public constructor( public _observable: Subscription, (...)

let observable = of (id_estado)
this._observable = observable.subscribe( (x:number) => {
} )

I was able to tie this together following some guides, even though Im not sure at all how Im supposed to recieve the data on the service, or why Im not using .next

When I save the previous component I get

Uncaught (in promise): NullInjectorError: StaticInjectorError(AppModule)[Component A]

How can I send data like this?

Upvotes: 0

Views: 207

Answers (1)

DaggeJ
DaggeJ

Reputation: 2201

With the current code you're trying to inject an observable as a dependency. Instead you should inject your service into both components A and B and provide a method in the service that component A calls and an Observable or an EventEmitter that component B can subscribe to.

Something like this;

Mediator service

@Injectable({
    providedIn: 'root'
})
export class MyService {

    public eventEmitter: EventEmitter<any> = new EventEmitter<any>();

    public methodThatCompnentACanCall(someValue: string) {
        this.eventEmitter.emit(someValue);
    }
}

constructor for both component A and B

public constructor(private mediator: MyService)

You may want to do a search for "the mediator pattern" for more info..

Upvotes: 1

Related Questions