我有两个共享服务的组件,第一个组件有2个按钮,点击squeezeContent()
和unsqueezeContent()
触发2个方法,这些方法将数值传递给服务中的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() { }
}
第二个组件
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
}
}
现在我希望在组件1中的 squeezeContent()和unqueezeContent()方法调用服务中的函数时更改 sidebarscrollheight属性值, sidebarscrollheight属性已经有一些计算值,请帮忙
答案 0 :(得分:0)
在Angular 2 Docs中查看本教程:https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service
这将有助于您了解如何通过可观察对象在组件之间进行通信。另外,请记得取消订阅e.q.来自你的观察者的this.subscription.unsubscribe()
。