2017-06-05 80 views
0

虽然我已经尝试了很多次,但没有工作EMIT或SUBSCRIBE。Angular2订阅不工作关于服务

我想隐藏的应用程序头,应用程序,工具条和app-页脚

LoginComponent。另外* ng如果不监听GlobalService变量。

在此先感谢您的支持。

/* App HTML */ 

<app-header *ngIf="global.showHeader"></app-header> 

<app-sidebar *ngIf="global.showSidebar"></app-sidebar> 

<div class="content-wrapper"> 
    <router-outlet></router-outlet> 
</div> 

<app-footer *ngIf="global.showFooter"></app-footer> 
/* AppComponent */ 

@Component({ 
    selector: 'app-root', 
    templateUrl: './app.component.html', 
    providers: [AppGlobalService] 
}) 
export class AppComponent implements OnInit{ 

    global = {}; 

    constructor(private globalService: AppGlobalService) { 

    this.globalService.listenUpdated.subscribe(

     data => { 

     this.global = data; 

     } 

    ); 
    } 

    ngOnInit(){ 
    } 
} 
/* AppGlobalService */ 

@Injectable() 
export class AppGlobalService { 

    data={ 
     showHeader: true, 
     showSidebar: true, 
     showFooter: true 
    }; 

    listenUpdated = new EventEmitter<any>(); 

    constructor(){} 

    updateStatus(key: any, value: any) { 
     this.data[key] = value; 
     console.log('SERVICE ', this.data); // It's working... 
    } 
} 
/* LoginComponent */ 

@Component({ 
    selector: 'app-login-index', 
    templateUrl: './index.component.html', 
    providers: [AppGlobalService] 
}) 
export class LoginIndexComponent implements OnInit { 

    private data = {}; 

    constructor(public globalService: AppGlobalService) { 
     this.globalService.updateStatus('showHeader', false); 
     this.globalService.updateStatus('showSidebar', false); 
     this.globalService.updateStatus('showFooter', false); 
     this.globalService.listenUpdated.emit(true); 
    } 

    ngOnInit() { 
    } 

} 

回答

0

我觉得自己像一个更好的方式做这将是有一个登录组件,然后让说,一个家庭的组成部分。 Login组件不会包含侧边栏或页脚的html或任何类似的东西。

当某人未通过身份验证时,您将使用路由路由到登录组件。一旦他们通过登录组件进行身份验证,您将路由到家庭组件,在此处会显示页脚和侧栏等内容。

整个guide to routing包括登录功能。所有这些都可以在现场看到。