我创建了在两个组件之间共享数据的服务,我阅读了文档并检查了几篇文章,但无法正确理解并陷入困境。
我创建了stackblitz,以学习作为数据共享的样本。这是链接 stackblitz
所以下面是我的代码 footer.component.ts
//trying to set value here
test(){
let height:any;
this.footerHeightService.setFooterHeight(height)
height = document.getElementById("footer").offsetTop;
}
footer-height.service.ts
import { Injectable } from '@angular/core';
@Injectable()
export class FooterHeightService {
footerOffset:any;
constructor() { }
setFooterHeight(height){
this.footerOffset = height;
}
getFooterHeight(height){
return this.footerOffset;
}
}
app.component.ts
//trying to get value here
constructor(private footerHeightService:FooterHeightService) { }
test(){
let height:any;
this.footerHeightService.getFooterHeight(height);
console.log("this.footerHeightService.getFooterHeight(height);", height);
}
ngOnInit():void{
this.test();
}
答案 0 :(得分:0)
首先,您需要创建一个服务
import { Injectable } from '@angular/core';
@Injectable()
export class SharedService {
constructor() { }
dataShared: any
setFooterData(data) {
this.dataShared = data
}
getFooterData() {
return this.dataShared
}
}
在组件页脚中,您将通过调用服务的方法集将数据发送到该服务
constructor(
...
private sharedService: SharedServiceService
) { }
componentMethod() {
this.sharedService.setFooterData(data)
}
在组件应用程序中,您将通过调用get方法获取数据
constructor(
...
private sharedService: SharedServiceService
) { }
componentMethod() {
this.sharedService.getFooterData()
}