0

I have two components that should be connected via Observable().

In the first i am declaring

@Injectable()
export class One{
    private changeConfirmed = new Subject<boolean>();

    changeConfirmed$ = this.changeConfirmed.asObservable();
    public init$: EventEmitter<boolean>;

    registerChangeConfirmed(category:boolean){
        alert('sending')
        this.changeConfirmed.next(category);
    }

    onMsg(){
        this.registerChangeConfirmed(true);
    }
}

onMsg is event bound to template

and in the second one

Import { One } from './pat/to/it'
@Component({
    providers:[One]
})

export class two{
    constructor( private childClass : One ){
        this.childClass.changeConfirmed$.subscribe( x => {alert(x)})
    }
}

However the event does not get emitted. But when i emit event in class two instead of class one = i include

this.childClass.registerChangeConfirmed(true)

in class two the event gets triggered. Why isn't it working when i invoke it from class one?

Thierry Templier
  • 198,364
  • 44
  • 396
  • 360
Johnyb
  • 980
  • 1
  • 12
  • 27

1 Answers1

0

Don't provide the service One on the component. This way each component instance will get its own One instance. If you provide it at a common parent (AppComponent) then they will get a shared instance.

Angular2 DI maintains an instance (singleton) per provider.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • u mean not adding providers:[ One ] to class Two component but to their parent? If so , this does not solve problem ( but might be usefull , thanks for that ) – Johnyb Jul 21 '16 at 13:04
  • Did you check `onMsg()` actually gets called? Can you please add the code that shows how you're doing it? – Günter Zöchbauer Jul 21 '16 at 13:06
  • Where do you include `this.childClass.registerChangeConfirmed(true)`. It's hard to see what's going on when only seeing fragments but not how they are actually related. – Günter Zöchbauer Jul 21 '16 at 13:11