【发布时间】:2019-01-22 13:46:04
【问题描述】:
我正在尝试将从一个组件中的服务接收到的数据共享到另一个组件,但得到空数据。
服务:
@Injectable()
export class AService {
private data = new BehaviorSubject<any>(null);
public data$ = this.data.asObservable();
getData(){
// http get service
}
setData(newData) {
this.data.next(newData);
}
}
组件 1:
@Component({
selector: "component1",
templateUrl: "../html/component1.html",
styleUrls: ["../css/component1.css"],
providers: [AService]
})
export class Component1 implements OnInit {
constructor(private aService: AService) {}
getData(corpId: string, type: string) {
this.aService
.getData
.subscribe(newData => {
this.aService.setData(newData);
// some other code.
});
}
}
组件 2:
@Component({
selector: "component2",
templateUrl: "../html/component2.html",
styleUrls: ["../css/component2.css"],
providers: [AService]
})
export class Component2 implements OnInit {
newData: any;
constructor(private aService: AService) {
this.aService.data$.subscribe(data => this.newData = data); // data is null as this statement is getting called first before the component 1
}
}
组件 2 构造函数在组件 1 getData() 方法之前被调用。两个组件都在同一个页面中,我希望先加载组件 1,然后再加载组件,以便将组件 1 中的数据获取到组件 2。
在另一个基本组件中,我使用了两个选择器,如下所示:
<component1></component1>
<component2></component2>
【问题讨论】:
-
您的代码甚至无法编译。发布可编译并重现您面临的问题的代码。不要放置 cmets 而不是与您的问题相关的关键代码。当你在做的时候,把它作为一个堆栈闪电发布,这样我们就可以看到问题的实际效果。
-
从概念上讲,您的组件应该按照描述的方式工作。但如果没有上述要求的有效堆栈闪电战,就很难看出是什么导致了问题。
-
你的代码在做两个简单的修改后就可以工作 1. 在服务私有数据更改为公共 2. 在组件 2 中 this.aService.data$ 更改为 this.aService.data
标签: angular typescript angular-components