i've started learning angular2 , i'm having trouble custom events using emit/subscribe.
i created little demo demonstrate: plunker
as can see, there previewservice class. class has seturl(url: string) method, that, if invoked, emits contenturlchange$ event.
src/services/preview.service.ts
import {injectable, eventemitter} 'angular2/core'; @injectable() export class previewservice { private _url: string; contenturlchange$: eventemitter<any>; constructor() { this.contenturlchange$ = new eventemitter; }; seturl(url: string): void { this._url = url; this.contenturlchange$.emit(url); }; }
in constructor function of app component, subscribe previewservice's contenturlchange$ event. if run plunker, see alert window.
src/app.ts
[...] constructor(private _previewservice: previewservice) { _previewservice.contenturlchange$.subscribe(url => { alert("app " + url); }) _previewservice.seturl('http://www.example.com'); }; [...]
but here problem: have component, previewcomponent, , in component's constructor function, in app component's constructor function, subscribe previewservice's contenturlchange$ event. strangely, alert window should appear, not.
src/component/preview.component.ts
constructor(private _previewservice: previewservice) { _previewservice.contenturlchange$.subscribe(url => { alert("preview " + url); // nothing happens here }) };
i read through couple of questions/answers, indicate i'm doing should working, still no success. thoughts/solutions appreciated. thx.
there few issues plunk. first things first, if inject separate instances of service components, won't able subscribe same event, because different variables(properties). must provide same service every component, in bootstrap of application:
bootstrap(app, [ yourservice ]).catch(...)
secondly, emmiting value app component when child component(previewcomponent
) not yet initialized. wait, use settimeout(func, 0)
(but hack , wouldn't recomend this), or use built in angular's oninit
lifecycle hook
import {oninit} 'angular2/core'; ... ngoninit() { // emit values here }
here updated plunk: http://plnkr.co/edit/okinpfrkkyxfce1p0d5o
Comments
Post a Comment