首页 > 解决方案 > 在 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 和订阅者的边界时被卡住了。我知道这是基本的东西,但它只是没有发挥作用。感谢任何帮助。

标签: angularobservablesubscriber

解决方案


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.


推荐阅读