【问题标题】:Need help in understanding how I can implement subscribe properly需要帮助了解如何正确实施订阅
【发布时间】:2017-03-23 01:55:14
【问题描述】:

场景

对于我的项目,我需要对 http 服务进行两次调用,我在一个函数中调用这两个函数:getData()。我需要两个数组的信息才能将其解析为另一个对象。

调用一次服务调用

  • getObjectData()

在此函数中,我将调用与 ID 对应的服务。我会用 Objects 返回一个数组。我需要对象 ID 和该对象的名称。

  • getSensorData()

每个 ObjectId 也有一个带有 SensorData 的 DeviceID,因此,从逻辑上讲,我为每个 ID 执行一个 for 循环以获取相应的数据。数据是一个数组,所以我需要sensorData[] 中每个 sensorData 的信息。

objects: TableData[];
otamObjects: OtamObject[];
sensorData: SensorData[];

因此,总而言之,我想要一个 TableData[] 填充数据,然后我可以使用这些数据填充表格。

代码:

我在 component.ts 中有以下代码

getData(): void {
    this.objects = new Array<TableData>();
    this.service.getObjectData(1)
        .subscribe(otamObject => {
            this.otamObjects = otamObject;
            console.log(JSON.stringify(this.otamObjects));
            for (let item of this.otamObjects) {
                console.log(JSON.stringify(item));
                var object = new TableData();
                object.Name = item.Name;
                object.ObjectId = item.OtamObjectId;
                (console.log('Create a new object' + JSON.stringify(object)));
                this.service.getSensorData(item.DeviceId)
                    .subscribe(response => {
                        for (let item of response) { // Forgive me for the following hard coded strings.                            
                            if (item.Key === 'Latitude') {
                                object.Latitude = item.Value;
                            }
                            if (item.Key === 'Longitude') {
                                object.Longitude = item.Value;
                            }
                            if (item.Key === 'Battery') {
                                object.Latitude = item.Value;
                            }
                            if (item.Key === 'Charging') {
                                object.Charging = item.Value;
                            }
                            if (item.Key === 'LocationType'){
                                if (item.Value === '1'){
                                    object.LocationType = "GPS";
                                } else {
                                    object.LocationType = "GSM";
                                }
                            }
                            object.LastActvity = item.CreatedDate;
                            console.log('Second for loop has finished: ' 
                            + JSON.stringify(object));                              
                        }
                        this.objects.push(object);
                        console.log("Second For loop has finished, pushing this object: " + JSON.stringify(object) + 
                        " to the array of objects: " + JSON.stringify(this.objects))
                    }, error => { console.log(<any>error); })
            }
            console.log('End of the first for loop, with data in Objects: ' + JSON.stringify(this.objects));
        },
        error => {
            console.log(<any>error);
        }
        );
};

在服务中我会拨打电话:

getObjectData(companyId: number): Observable<OtamObject[]> {
    return this.http.get(this.actionUrl + "otamObject/" + companyId, this.headers)
        .map((response: Response) => <OtamObject[]>response.json())
        .catch(this.handleError);
}

getSensorData(deviceId: number): Observable<SensorData[]> {
    return this.http.get(this.actionUrl + "sensorData/deviceId/" + deviceId, this.headers)
        .map((response: Response) => <SensorData[]>response.json())
        .catch(this.handleError);
}

问题

我提出这个问题的原因是,现在,正如您在 output 中看到的那样,第一个 for 循环在其他所有操作之前完成,但这不是我想要的。我想要三个对象,然后他需要为每个对象执行第二个 for 循环。

我不完全理解如何解决这个问题,在任何其他编程语言中,第一个 for 循环应该在最后一个之前等待,所以它会这样做,但是因为我得到了订阅,所以它只是完成了循环。我知道这与第二次订阅有关。无论如何,处理这个问题的正确方法是什么。

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    for 循环不会等待订阅完成。因为 observable 函数是异步运行的。可能想使用async 库之类的东西,将回调添加到 for 循环。

    【讨论】:

    • 可以用mergeMap或类似的操作符修复
    • @GünterZöchbauer,您的回答让我寻找正确的操作和答案。虽然提供的东西“很好”,但我想,我认为不使用可用的正确工具并使用另一个第三方库并不是很好的做法。又一个依赖。
    猜你喜欢
    • 1970-01-01
    • 2016-12-14
    • 2016-02-24
    • 2020-07-06
    • 1970-01-01
    • 2021-11-16
    • 2011-10-26
    • 2017-06-19
    • 2016-05-03
    相关资源
    最近更新 更多