In my project, I have implemented two components that share a service. The first component contains 2 buttons which trigger the methods squeezeContent()
and unsqueezeContent()
on click. These methods pass a numeric value to an observable in the shared service. This value is then subtracted from a property in another component that also shares the same service. I have been struggling to correctly utilize observables in this scenario.
First Component
import { Component, AfterViewInit, ElementRef, ViewChild } from '@angular/core';
import { CrosspropertiesService } from "../services/crossproperties.service";
@Component({
selector: 'app-timer',
templateUrl: './timer.component.html',
styleUrls: ['./timer.component.css']
})
export class TimerComponent implements AfterViewInit {
@ViewChild('timerBody') timerBody:ElementRef;
constructor(private crossproperties: CrosspropertiesService ) { }
public timerBodyHeight:number;
ngAfterViewInit() {
this.timerBodyHeight = this.timerBody.nativeElement.offsetHeight;
}
squeezeContent(){
this.crossproperties.resizeHeight(this.timerBodyHeight);
}
unsqueezeContent(){
this.crossproperties.resizeHeight(0);
}
}
Service File
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { Subject } from 'rxjs/Subject';
@Injectable()
export class CrosspropertiesService {
private subject = new Subject<any>();
resizeHeight(height:number){
this.subject.next({ value: height });
}
getSidebarScrollHeight(): Observable<any>{
return this.subject.asObservable();
}
constructor() { }
}
Second Component
import { Component, OnInit , OnDestroy, ElementRef, ViewChild} from '@angular/core';
import { CrosspropertiesService } from '../services/crossproperties.service';
import { Subscription } from 'rxjs/Subscription';
@Component({
selector: 'app-sidebar-expanded',
templateUrl: './sidebar-expanded.component.html',
styleUrls: ['./sidebar-expanded.component.css']
})
export class SidebarExpandedComponent implements OnInit {
subscription:Subscription;
private sidebarscrollheight:number;
constructor(private crossproperty: CrosspropertiesService) {
this.subscription = this.crossproperty.getSidebarScrollHeight().subscribe(height => { this.sidebarscrollheight = this.sidebarscrollheight - height; });
}
ngOnInit() {
this.sidebarscrollheight = 600; //computed value in this section
}
}
Now, I need assistance with updating the value of the sidebarscrollheight property when the squeezeContent() and unsqueezeContent() methods in component 1 call the function in the shared service. The sidebarscrollheight property already holds a computed value. Any help would be greatly appreciated.