角度2:事件未触发

时间:2016-08-01 10:54:00

标签: javascript angularjs angular angular2-template angular2-changedetection

当我的组件从服务获取已记录的用户时,我正在尝试触发事件,因为我只想在用户登录时显示导航栏。

这是我的app.component代码:

import { Component, OnInit, EventEmitter, Input, Output } from '@angular/core';
import { ROUTER_DIRECTIVES, Router } from '@angular/router';
import { LoginComponent } from './login.component';
import { DashboardComponent } from './dashboard.component';
import { ControlDetailComponent } from './control-detail.component';
import { PageNotFoundComponent } from './pagenotfound.component';
import { SettingsComponent } from './settings.component';
import { UserService } from '../service/user.service';
import { User } from '../object/user';

@Component({
    selector: 'myApp',
    templateUrl: './app/template/app.component.html',
    styleUrls: ['styles.css'],
    directives: [ROUTER_DIRECTIVES],
    precompile: [LoginComponent, DashboardComponent, ControlDetailComponent, PageNotFoundComponent, SettingsComponent]
})
export class AppComponent {
    @Input() loggedUser:User;
    @Output() userChanged:EventEmitter<User> =  new EventEmitter<User>();

    constructor(private _userService:UserService, private _router:Router) {}

    ngAfterViewInit() { 
        if(this._userService.isUserLogged()) {
           this.userChanged.emit(this._userService.loggedUser);
       }
    }

    switchUser(event) {
        this.loggedUser = event.target.value;
        console.log("event triggered");
    }
}


这是它的相关模板:

<div class="all-content">
<nav (userChanged)="switchUser($event)" *ngIf="loggedUser">
    <ul>
        <a [routerLink]="['/dashboard']" routerLinkActive="active">Dashboard</a>
        <a [routerLink]="['/settings']" routerLinkActive="active">Settings</a>
        <a (click)="logout()">Logout</a>
    </ul>
</nav>


有人知道为什么我的事件没有被解雇?

最初我认为问题是阻止事件触发的*ngIf指令,但即使删除它,事件也不会被触发......

2 个答案:

答案 0 :(得分:3)

@Output()发出的事件只能在父组件上或在元素上应用的指令上订阅。 AppComponent没有父组件,因此这种方法无法正常工作。

在您的情况下,最好将共享服务与observable一起使用。 https://angular.io/docs/ts/latest/cookbook/component-communication.html

答案 1 :(得分:3)

使用ObservablesService解决,正如GünterZöchbauer所建议的那样(谢谢!)。

在我的解决方案之下:

<强> user.service.ts

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import { Subject }    from 'rxjs/Subject';
import { Control } from '../object/control';
import { User } from '../object/user';


@Injectable()
export class UserService {
    private userChangedSource = new Subject<User>();
    userChanged = this.userChangedSource.asObservable();
    loggedUser:User;

    userLoggedIn(user:User) {
        this.loggedUser = user;
        this.userChangedSource.next(user);
    }

    ...
}

<强> app.component.ts

import { Component, OnInit, EventEmitter, Input, Output } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { ROUTER_DIRECTIVES, Router } from '@angular/router';
import { LoginComponent } from './login.component';
import { DashboardComponent } from './dashboard.component';
import { ControlDetailComponent } from './control-detail.component';
import { PageNotFoundComponent } from './pagenotfound.component';
import { SettingsComponent } from './settings.component';
import { UserService } from '../service/user.service';
import { User } from '../object/user';

@Component({
    selector: 'myApp',
    templateUrl: './app/template/app.component.html',
    styleUrls: ['styles.css'],
    directives: [ROUTER_DIRECTIVES],
    precompile: [LoginComponent, DashboardComponent, ControlDetailComponent, PageNotFoundComponent, SettingsComponent]
})
export class AppComponent implements OnInit {
    loggedUser:User;

    constructor(private _userService:UserService, private _router:Router) { 
        this._userService.userChanged.subscribe(user => {
                this.loggedUser = user;
                console.log("event triggered");
        });
    }
    ...
}

<强> app.component.html

<div class="all-content">
    <nav *ngIf="loggedUser" >
        <ul>
            <a [routerLink]="['/dashboard']" routerLinkActive="active">Dashboard</a>
            <a [routerLink]="['/settings']" routerLinkActive="active">Settings</a>
            <a (click)="logout()">Logout</a>
        </ul>
    </nav>
<router-outlet></router-outlet>
<br/>
</div>