Not receiving subscribed subject

28 Views Asked by At

I want to use a service to subscribe a subject with a boolean as a value.

My Header.component listens to a scroll event an sets the subjects value depending on if the title is out of view or not.

My navigation.component subscribed the subject but it is not receiving the value.

scrollService:

import { Injectable, EventEmitter } from '@angular/core';
import { Subject } from 'rxjs/internal/Subject';

@Injectable({
  providedIn: 'root'
})

export class ScrollService {

  titleScrolledOut = new Subject<boolean>();

  titleInView(value: boolean) {
    this.titleScrolledOut.next(!value);
  }

  constructor() { }
}

Header.component:

import { Component, ElementRef, EventEmitter, HostListener, Output, ViewChild } from '@angular/core';
import { ScrollService } from '../scroll.service';

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.scss'],
  providers: [ScrollService]
})
export class HeaderComponent {
  constructor(private scrollService: ScrollService) {}

  @ViewChild('titleLogo') titleDiv!: ElementRef;

  @HostListener('document:scroll', ['$event'])

  public onViewportScroll() {
    const windowHeight = window.innerHeight;
    const titleBoundingRect = this.titleDiv.nativeElement.getBoundingClientRect();

    if (titleBoundingRect.top < 0 || titleBoundingRect.bottom > windowHeight) {
      this.scrollService.titleInView(true);
    } else {
      this.scrollService.titleInView(false);
      
    }
  }
}

Navigation.component (with the "NgOnInit" in which I subscribed the Subject):

import { Component, Input, OnInit } from '@angular/core';
import { ScrollService } from '../scroll.service';

@Component({
  selector: 'app-navigation',
  templateUrl: './navigation.component.html',
  styleUrls: ['./navigation.component.scss'],
  providers: [ScrollService]
})
export class NavigationComponent implements OnInit {
  constructor(private scrollService: ScrollService) { }

  bodyElement = document.getElementsByTagName('body')[0];
  showOverlayMenu: boolean = false;

  @Input() burgermenu: boolean = false;
  @Input() showName: boolean = false;

  ngOnInit(): void {
    this.scrollService.titleScrolledOut.subscribe((value) => {
      console.log('showName = :')
      this.showName = value;
    });
  }

  toggleBurgerMenu() {
    this.showOverlayMenu = !this.showOverlayMenu;
    
this.bodyElement.style.overflowY = this.showOverlayMenu ? 'hidden' 
: 'scroll';
  }

}

I also tried the same with eventemitter and nothing worked.

1

There are 1 best solutions below

0
Matthieu Riegler On

You're providing a new ScrollService by having providers: [ScrollService] in your NavigationComponent.

Remove it and you'll have the expected behaviour.