【问题标题】:Subscribe to voluminous object in angular以角度订阅大量对象
【发布时间】:2018-04-13 08:46:02
【问题描述】:

我一直在通过 get 请求获取对象。

我在component.ts中有如下函数

private _getPolygonById(id: number) {
    let poly: any;
    this.dataService.getCollectionbyId(id).subscribe(data => {
        const res = data.json();
        poly = JSON.parse(res.string);
    });
    return poly;
}

我的 service.ts 包含以下内容:

getCollectionbyId(id: number) {
    console.log("launching request");
    return this.http.get('api/project-collections/'+id);
}

问题是 poly 未定义并按原样返回,响应被异步处理。我怎样才能等待请求,直到它得到响应,然后将它影响到 poly,返回它?

【问题讨论】:

    标签: angular angular4-httpclient


    【解决方案1】:

    如您所知,_getPolygonById 函数会在您获得更改以在 subscribe 块中获取结果之前返回。操作顺序如下:

    private _getPolygonById(id: number) {
        let poly: any; // 1
        this.dataService.getCollectionbyId(id).subscribe(data => {
            // 3
            const res = data.json();
            poly = JSON.parse(res.string);
        });
        return poly; // 2
    }
    

    您应该从 _getPolygonbyId 函数返回 observable 并在您想要使用它时订阅结果。

    ngOnInit() {
      this._getPolygonById(5).subscribe(// do something with the returned polygon)
    }
    
    private _getPolygonById(id: number): Observable<any> {
        return this.dataService.getCollectionbyId(id);
    }
    

    【讨论】:

    • getPolygonById 是通过点击事件调用的,所以我不知道会被调用的 id。并且获取的数据非常庞大。
    猜你喜欢
    • 1970-01-01
    • 2020-11-21
    • 1970-01-01
    • 1970-01-01
    • 2020-12-18
    • 2018-08-22
    • 2021-01-20
    • 2021-09-22
    • 2021-01-10
    相关资源
    最近更新 更多