在Angular 2中发出事件后如何订阅 [英] How to subscribe after the emitting the event in Angular 2

查看:99
本文介绍了在Angular 2中发出事件后如何订阅的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

遵循此答案中提供的步骤-

Following the steps provided in this answer - Angular2: Using routes, how to display the navigation bar after successfully logged in?

该事件在login.component.ts的承诺"中发出,并且有望在navbar.component.ts的构造函数中达到订阅",但没有达到.我想念什么?下面是代码:

The event is emitted in the "promise" of login.component.ts and is expected to hit "subscribe" in the constructor of navbar.component.ts but it's not hitting. What am I missing? Below is the code:

Main.ts

import { bootstrap } from 'angular2/platform/browser';    
    // Our main component
    import { AppComponent } from './app.component';
    import { GlobalEventsManager } from './globaleventsmanager';
    import {ROUTER_PROVIDERS} from 'angular2/router';
    
    bootstrap(AppComponent, [GlobalEventsManager, ROUTER_PROVIDERS]);

App.component.ts

App.component.ts

    import { Component } from 'angular2/core';
    import { LoginComponent } from './home/login.component';
    import { WelcomeComponent } from './home/welcome.component';
    import { HTTP_PROVIDERS }  from 'angular2/http';
    import { RouteConfig, ROUTER_DIRECTIVES } from 'angular2/router';
    import { TopNavbarComponent } from './navbar.component';
    
    @Component({
        selector: 'cmt-app',
        template: `<div class='container'>
                        <navbar></navbar>
                        <router-outlet></router-outlet>
                    </div>
                `,
        directives: [ROUTER_DIRECTIVES, TopNavbarComponent],
        providers: [HTTP_PROVIDERS]
    })
    
    @RouteConfig([
            { path: '*', name: 'Login', component: LoginComponent, useAsDefault: true },
            { path: '/welcome', name: 'Welcome', component: WelcomeComponent }
    ])
    
    export class AppComponent {
        
    }

GlobalEventsManager.ts

GlobalEventsManager.ts

import { EventEmitter, Injectable } from "angular2/core";
import { IUserDetails } from "./home/login";

@Injectable()

export class GlobalEventsManager {
    public showNavBar: EventEmitter<boolean> = new EventEmitter();


    constructor() {

    }
}

Navbar.component.ts

Navbar.component.ts

     import {Component, ViewEncapsulation, OnInit} from "angular2/core";
    import {GlobalEventsManager} from "./globaleventsmanager";
    import { IUserDetails } from '././home/login';
    
    @Component({
        selector: "navbar",
        templateUrl: '/app/navbar.component.html',
        encapsulation: ViewEncapsulation.None
    })
    
    export class TopNavbarComponent {
        showNavBar: boolean = false;
        menuItems: IUserDetails[] = [];
    
        constructor(private globalEventsManager: GlobalEventsManager) {
            this.globalEventsManager.showNavBar.subscribe((data: boolean) => {
                console.log('reached');
                //this.menuItems.push(data);
                this.showNavBar = true;
                console.log(this.menuItems);
                //console.log(this.showNavBar);
            }, error => console.log(error));
    
        }
    }

Login.component.ts

Login.component.ts

import { Component, Output, EventEmitter } from 'angular2/core';
import { Http, Response, Headers, RequestOptions } from 'angular2/http';
import { Observable }  from 'rxjs/Observable';
import { CommonService } from '../services/common.service';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import { IUserDetails } from '../home/login';
import { GlobalEventsManager } from './../globaleventsmanager';
import { Router } from 'angular2/router';

@Component({
    templateUrl: 'app/home/login.component.html',
    providers: [CommonService, GlobalEventsManager]
})

export class LoginComponent {
    private _commonServiceUrl = 'http://localhost:58116/api/common/initializemenuitems';

    constructor(private _router: Router, private _commonService: CommonService, private globalEventsManager: GlobalEventsManager) {
    }

    accountName: string = '';
    loginId: string = '';
    password: string = '';
    menuItems: IUserDetails[] = [];
    errorMessage: any[];

    loginUser(): void{
        this._commonService.loginUser(this.accountName, this.loginId, this.password, 'common', 'initializemenuitems')
            .subscribe(data => this.promise(data), error => this.errorMessage = <any>error);
    }

    private promise(data: IUserDetails) {
        this.globalEventsManager.showNavBar.emit(true);
        this._router.navigate(['Welcome']);

    }

    private handleError(error: Response) {
        console.error(error);
        return Observable.throw(error.json().error || 'Server error');
    }
}

推荐答案

当您引用在中的boostrap参数中创建的GlobalEventsManager对象的单例实例时,无意中创建了GlobalEventsManager对象的新实例.Main.ts

从LoginComponent中的提供者删除对GlobalEventsManager的引用,它应该可以正常工作.

Remove the reference to GlobalEventsManager from providers in the LoginComponent and it should work as expected.

这篇关于在Angular 2中发出事件后如何订阅的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆