【发布时间】:2020-08-11 06:51:24
【问题描述】:
我开始使用天气 api 制作我的第一个 angular 应用程序,在第一个加载视图中,我想通过订阅 observables 来发出 3 个请求,所有三种类型的 get 都取决于以下内容:
1 - 获取所有状态的列表 2 - 获取每个州的部门列表 3 - 从每个随机状态获取一个部门的预测
我要面对的问题是,在发出不同的连接请求时,我不想在所有加载完成之前加载数据表,但这让我非常困难,因为我试图把代码开头的加载变量和 for 末尾的另一个加载变量存在于第 2 点和第 3 点之间,但它不能按预期工作。
我的代码如下:
general.component.ts:
import { Component, OnInit } from '@angular/core';
import { eltiempoDataService } from 'src/app/services/eltiempo-data.service';
import { weatherGeneralModel } from 'src/app/models/weatherGeneral.model';
@Component({
selector: 'app-general',
templateUrl: './general.component.html',
styleUrls: ['./general.component.css']
})
export class GeneralComponent implements OnInit {
data_mun: weatherGeneralModel[] = [];
loading_data: boolean;
constructor(private eltiempoDataService: eltiempoDataService) {
this.getRandomMunicipio()
console.log('finish2')
}
ngOnInit() {
}
getRandomMunicipio() {
let provs
let prov_random: {}
this.getProvincias().subscribe((data: any[]) => {
this.loading_data = true;
provs = data['provincias']
this.processData(provs)
})
}
processData(provs: any[]){
for (let prop in provs) {
this.getMunicipios(provs[prop]['CODPROV']).subscribe((data_municipios) => {
let object_data_general: weatherGeneralModel = new weatherGeneralModel()
let local_muni: any[] = data_municipios['municipios']
var random = Math.floor(Math.random() * local_muni.length);
let cod_ine_mun = local_muni[random]['CODIGOINE'].toString().substring(0, 5);
this.getDataMunicipio(provs[prop]['CODPROV'], cod_ine_mun).subscribe((data_predict) => {
object_data_general.comunidad = provs[prop]['COMUNIDAD_CIUDAD_AUTONOMA']
object_data_general.provincia = provs[prop]['NOMBRE_PROVINCIA']
object_data_general.municipio = data_predict['municipio']['NOMBRE']
object_data_general.pronostico = data_predict['temperaturas']['max'] + '/' + data_predict['temperaturas']['min']
object_data_general.cod_prov = provs[prop]['CODPROV']
this.data_mun.push(object_data_general)
})
})
}
this.loading_data = false;
}
getProvincias() {
return this.eltiempoDataService.getProvincias()
}
getMunicipios(cod_prov: string) {
return this.eltiempoDataService.getMunicipios(cod_prov)
}
getDataMunicipio(cod_prov: string, id_muni: string) {
return this.eltiempoDataService.getDataMunicipio(cod_prov, id_muni)
}
}
eltiempo-dataService.service.ts:
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class eltiempoDataService {
constructor(private http: HttpClient) {
console.log('servicio ElTiempo.net listo')
}
getProvincias(){
return this.http.get('https://www.el-tiempo.net/api/json/v2/provincias')
}
getMunicipios(cod_prov:string){
return this.http.get(`https://www.el-tiempo.net/api/json/v2/provincias/${cod_prov}/municipios`)
}
getDataMunicipio(cod_prov:string, id_muni:string){
return this.http.get(`https://www.el-tiempo.net/api/json/v2/provincias/${cod_prov}/municipios/${id_muni}`)
}
}
general.component.html:
<div class="contianer mt-5 m-sm-5">
<div class="table-responsive">
<table class="table table-striped table-dark" *ngIf="!loading_data">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Comunidad</th>
<th scope="col">Provincia</th>
<th scope="col">Muicipio</th>
<th scope="col">Prediccion</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let data of data_mun">
<th scope="row">{{data.CODPROV}}</th>
<td>{{data.comunidad}}</td>
<td>{{data.provincia}}</td>
<td>{{data.municipio}}</td>
<td>{{data.pronostico}}</td>
</tr>
</tbody>
</table>
</div>
</div>
我认为我没有遵循最佳做法,如果有任何帮助、建议和指导,我将不胜感激。
谢谢大家
【问题讨论】:
-
您需要将
this.loading_data = false;放在最深的嵌套订阅中,因为订阅是async,因此您的标志大部分时间会在实际加载数据之前执行。另外你不应该嵌套subscribes,它会给出时间错误并且更难进行错误处理。 This article will explain what to do instead of using nested subscriptions 或者您可以查看RxJS website。
标签: javascript angular typescript get observable