1

I have problem to show or hide my headerbar using observable and subject of rxjs.

I have a headerbar, and I wanted to show / hide depending on the called screen.

For example :

When I'm on the login screen, my headerbar will not be displayed! However, when I enter the system, it will display my headerbar.

I use the following codes for example:

headerbar.component.ts :

import { Component } from '@angular/core';
import { GlobalService } from '../global.service';


@Component({
    moduleId: module.id,
    selector: 'fnd-headerbar',
    templateUrl: 'headerbar.component.html',
    providers:[GlobalService]
})
export class HeaderbarComponent { 
    private showHeaderbar : boolean = true;

    constructor(private globalService : GlobalService) {
        this.globalService.headerbarApi.showHeaderbar$.subscribe((show) => {
            this.showHeaderbar = show;
        });
    }
}

headerbar.component.html

<nav class="navbar navbar-default navbar-xs fnd-nav-bar fnd-nav-bar-primary" *ngIf="showHeaderbar" >
    <div class="fnd-div-menu">
        <div style="display: table-row">    
...

headerbar.api.ts

import { Observable } from 'rxjs/Rx';
import { Subject }    from 'rxjs/Subject';

export class HeaderbarApi {
    public showHeaderbar$ : Observable<boolean>;

    public showHeaderbarSource = new Subject<boolean>();
    constructor() {
        this.showHeaderbar$ = this.showHeaderbarSource.asObservable(); 
    }
    public showHeaderbar(show : boolean) {
        this.showHeaderbarSource.next(show);
    }
}

global.service.ts

import { HeaderbarApi } from './headerbar/headerbar.api';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Rx';
import { Subject }    from 'rxjs/Subject';

@Injectable()
export class GlobalService {

    public headerbarApi : HeaderbarApi = new HeaderbarApi();

    constructor() {}

}

login.component.ts

import { Component } from '@angular/core';
import { GlobalService } from '../../+foundation/global.service';

@Component({
    moduleId: module.id,
    selector: 'fnd-login',
    templateUrl: 'login.component.html',
    providers: [GlobalService]
})
export class LoginComponent implements OnInit {

    constructor(private globalService : GlobalService) {
    }
    public ngOnInit() : void {
        this.globalService.headerbarApi.showHeaderbar(false);
    }
}
user1875730
  • 113
  • 7
  • You provide 2 `GlobalService` in 2 components, that results in 2 instances of `GlobalService` being created, and changes of one will not affect the other. Remove all `providers: [GlobalService]` lines in your components and put it to your module. – Harry Ninh May 24 '17 at 01:43
  • I love you! You sava my life haha @HarryNinh – user1875730 May 24 '17 at 02:01
  • 2
    Possible duplicate of [Angular - sharing data between components with a service](https://stackoverflow.com/questions/43997489/angular-sharing-data-between-components-with-a-service) – eko May 24 '17 at 04:50

0 Answers0