Angular 通过在角度2中的可观察性更改组件的属性值

Angular 通过在角度2中的可观察性更改组件的属性值,angular,typescript,angular2-services,Angular,Typescript,Angular2 Services,我有两个组件共享一个服务,第一个组件有两个按钮,在单击squezecontent()和unsquezecontent()时触发两个方法,这些方法将一个数值传递给服务中可观察的对象,然后从共享同一服务的另一个组件的属性中减去该值,我一直在尝试使用observable,但我做得不对 第一个组件 import { Component, AfterViewInit, ElementRef, ViewChild } from '@angular/core'; import { Crosspropertie

我有两个组件共享一个服务,第一个组件有两个按钮,在单击
squezecontent()
unsquezecontent()
时触发两个方法,这些方法将一个数值传递给服务中可观察的对象,然后从共享同一服务的另一个组件的属性中减去该值,我一直在尝试使用observable,但我做得不对

第一个组件

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);
         }
}
和服务文件

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() { }
}

现在我希望当组件1中的squeezeContent()和unsquezeContent()方法调用服务中的函数时,sidebarscrollheight属性已经有一些计算值,有任何帮助请查看Angular 2文档中的本教程:

这将有助于您了解如何通过可观察对象在组件之间进行通信。另外,请记住从您的观察对象中取消订阅e.q.
this.subscription.unsubscribe()

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
  }  
}