首页 文章

在Angular 5中观察一个函数

提问于
浏览
0

I think I don't understand Observables . 我有2个组件 ChartsComponent ,让我们说 AppComponent . AppComponent从数据库中获取信息并将其通过 ChartsService 传递给ChartsComponent进行绘制 . 事情是ChartsComponent的选择器 <charts></charts> 同时加载到AppComponent中,因此数据库数据到达ChartsComponent after construction . 我以为我可以使用Observable监视数据库响应并更新ngIf布尔变量以加载选择器并构建ChartsComponent .

App.component.html:

<div *ngIf="chartsBoolean">
    <charts-component-selector></charts-component-selector>
</div>

App.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 =>只是Getters和Setters

Charts.Component.ts

constructor( private chartsService: ChartsService ){

    this.chartsService.getChartData();

    );
}

正如您所看到的那样,在规划Observable和订户的边界时我只是陷入困境 . 我知道这是基本的东西,但它只是没有踢 . 任何帮助表示赞赏 .

1 回答

  • 0

    所以我找到了答案,但忘记发布了 .

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

    通过在ChartsService中设置所需的值后将chartsBoolean更改为“true”,可以在构造时为ChartsComponent提供值 . OnSuccess可以花时间从数据库中获取数据,并且在它访问该数据之前永远不会构建ChartsComponent .

相关问题