angular - 在 Angular 5 中观察一个函数
问题描述
我想我不明白 Observables。我有 2 个组件ChartsComponent,比如说AppComponent。AppComponent 从数据库中获取信息并通过ChartsService将其传递给 ChartsComponent 以进行绘制。问题是 ChartsComponent 的选择器同时加载到 AppComponent 内部,因此数据库数据在构建后<charts></charts>
到达 ChartsComponent 。我想我可以使用 Observable 来监视数据库响应并更新 ngIf 布尔变量来加载选择器并构建 ChartsComponent。
App.component.html:
<div *ngIf="chartsBoolean">
<charts-component-selector></charts-component-selector>
</div>
应用程序.component.ts。我会在构造函数中启动 Observable 吗?
constructor( private chartsService: ChartsService ){
var chartsBoolean = false;
var myObservable = new Observable(observer =>{
this.chartsBoolean = true;
})
let subscription = myObservable.subscribe(
);
}
//this is the method I think I should be monitoring
getChartDataFromDatabase(){
//onSuccess inserts database response into charData
this.chartsService.setChartData(charData);
}
Charts.service.ts => 只是 Getter 和 Setter
Charts.Component.ts
constructor( private chartsService: ChartsService ){
this.chartsService.getChartData();
);
}
正如你所看到的,我在规划 Observable 和订阅者的边界时被卡住了。我知道这是基本的东西,但它只是没有发挥作用。感谢任何帮助。
解决方案
So I worked out an answer but forgot to post it.
app.component.html
...
<div *ngIf="chartsBoolean">
<charts-component-selector></charts-component-selector>
</div>
...
app.service.ts
query(): Observable<HttpResponse<any[]>> {
return this.http.get<any[]>(this.resourceUrl, { params: options, observe: 'response' })
.map((res: HttpResponse<any[]>) => this.convertArrayResponse(res));
}
app.component.ts
loadCharts(){
this.chartsBoolean = false;
this.AppService.query().subscribe(
(res: HttpResponse < string[] > ) => this.onSuccess(res.body),
(res: HttpErrorResponse) => this.onError(res.message)
);
}
private onSuccess(data){
this.chartsService.setChartData(data);
this.chartsBoolean = true;
}
By changing chartsBoolean to "true" after setting the values you need in ChartsService, tha values are available on construction for the ChartsComponent. OnSuccess can take it's time to get triggered with data from Database, and ChartsComponent is never built before it has access to that data.
推荐阅读
- laravel - 为什么对字符串字段的唯一验证在 laravel 中不起作用?
- python - 有没有办法将过滤后的数据帧打印到 tkinter 标签上
- javascript - 鼠标视差
- python - 子流程输出不拆分
- typescript - 为什么我不能使用 switch 语句来缩小 Typescript 中的类类型?
- ionic-framework - 未捕获(承诺):TypeError:无法访问离子段中的属性“值”
- ios - 快速解码 JSON 中的唯一键或忽略某些键
- bash - 复制Linux目录结构/树**仅**没有文件并保留属性
- html - css:是否可以在父元素内部移动子元素,以便父元素自动调整大小
- arrays - c中数组的冒泡排序