1

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

这是我的 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阻止触发事件的指令,但是即使删除它,事件也不会被触发......

4

2 回答 2

3

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

在您的情况下,最好使用带有 observables 的共享服务。 https://angular.io/docs/ts/latest/cookbook/component-communication.html

于 2016-08-01T11:04:12.577 回答
3

正如 Günter Zöchbauer 建议的那样,使用Observables和 a解决了(谢谢!)。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>
于 2016-08-01T14:38:22.780 回答