Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 EventEmitter

I have an issue where the EventEmitter does not output the value to parent component. Here is how i am setup.

main.component.ts (short version)

...     

@Component({
selector: 'my-app',
templateUrl: '/app/views/main.ejs',
directives: [ROUTER_DIRECTIVES],
providers:[AuthService],
inputs:['userLoggedIn']
})

@RouteConfig([
{path:'/logout', name: 'Logout', component: AuthComponent},

])

export class AppComponent implements OnInit, CanReuse{  

    constructor(private _auth_service: AuthService){

         this._auth_service.authChanged.subscribe(data=>this.authChangedHandler(data));

    }

    public authChangedHandler($event){

        alert($event);

    }

}

...

auth.component.ts (short version)

export class AuthComponent implements OnInit, CanReuse{

public loggedIn = false;

public user = {};

@Output()
authChanged: EventEmitter<string>;

public selectedTab = "/login";

    constructor(private _router: Router, private _location:Location,private _http: Http, private _auth_service: AuthService){

        this.authChanged = new EventEmitter();

        this.authChanged.emit("authChanged");

    }

}

main.ejs (short version)

<nav (authChanged)="authChangedHandler($event)"></nav>
<router-outlet></router-outlet>

auth.service.ts

export class AuthService {

public authChanged: EventEmitter<string>;

constructor(private _http: Http){

    this.authChanged = new EventEmitter();
    this.authChanged.emit("authChanged");

    }

}

EDIT: I have added AuthService code which i inject into main component. It should work now but does not.

like image 823
xmaestro Avatar asked Feb 12 '16 13:02

xmaestro


2 Answers

Events emitted by EventEmitter don't bubble. If the element is added to a router-outlet only the router-outlet receives the event but not the element containing the router-outlet.

You could use a shared service to communicate between the parent and the child element.

For shared service see

  • https://github.com/escardin/angular2-community-faq/blob/master/services.md#how-do-i-communicate-between-components-using-a-shared-service
  • Global Events in Angular 2

If you register the shared service in the providers: [] list of the parent component, the service is shared only between the parent element and all of its descendants. If you only add it to bootstrap(MyApp, [ ..., SharedService]) the whole application shares one instance.

like image 76
Günter Zöchbauer Avatar answered Oct 28 '22 01:10

Günter Zöchbauer


In fact, the nav isn't the parent component of the AuthComponent one. The latter is involved in routing (see router-outlet). That's why you can't receive the event for the registered expression on the nav element in the HTML.

like image 45
Thierry Templier Avatar answered Oct 28 '22 00:10

Thierry Templier