【发布时间】:2020-10-06 16:17:26
【问题描述】:
我正在开发来自 OpenWeatherMap API 的天气应用程序,由于请求太多,我已经两次阻止了我的服务。我检查了我的代码很多次,我找不到一个会导致服务器循环需求的地方,我检查了控制台,它给出了以下错误:ERROR TypeError: ctx.amindiDGES is undefined .
我在 main.component.html 的几行中收到此错误:
MainComponent_Template main.component.html:8
getLocation main.component.ts:39
ngOnInit main.component.ts:27
这就是我的服务的样子 today.service.ts
import { Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError, retry } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class TodayService {
url = 'http://api.openweathermap.org/data/2.5/weather';
apiKey = '***********************';
constructor(private http: HttpClient) { }
daitriecoordinatebi(lat, lon) {
let params = new HttpParams()
.set('lat', lat)
.set('lon', lon)
.set('units', 'metric')
.set('appid', this.apiKey)
return this.http.get(this.url, { params });
这是我的 main.component.ts
import { Component, OnInit } from '@angular/core';
import { TodayService } from './today.service';
@Component({
selector: 'app-main',
templateUrl: './main.component.html',
styleUrls: ['./main.component.scss']
})
export class MainComponent implements OnInit {
lat;
lon;
amindiDGES;
kvirisdgeToday;
ikonkaToday;
title = 'Day1';
today = new Date();
constructor(private todayService: TodayService) { }
ngOnInit(): void {
// lokacia
this.getLocation();
// zusti saati
this.today = new Date();
}
getLocation() {
if ("geolocation" in navigator) {
navigator.geolocation.watchPosition((success) => {
this.lat = success.coords.latitude;
this.lon = success.coords.longitude;
this.todayService.daitriecoordinatebi(this.lat, this.lon).subscribe(data => {
this.amindiDGES = data;
})
})
}
}
}
这是我的 main.component.html
的一部分<table>
<tbody>
<tr>
<td><i class="fas fa-wind"></i></td>
<td> Wind - {{amindiDGES.wind.speed}}</td>
</tr>
<tr>
<td><i class="far fa-eye"></i></td>
<td> Visibility - {{amindiDGES.visibility}}</td>
</tr>
<tr>
<td><i class="fas fa-tachometer-alt"></i></td>
<td> Preassure - {{amindiDGES.main.pressure}}</td>
</tr>
<tr>
<td><i class="fas fa-tint"></i></td>
<td> Humidity - {{amindiDGES.main.humidity}}</td>
</tr>
</tbody>
</table>
所有这一切的有趣之处在于,我从服务器获取数据并且确实看到了结果,但不知何故,由于需求过多,应用程序在使用几次后被阻止,允许的数量是每分钟 60 次,而我的应用程序每分钟需要 800 多个请求,除此之外,控制台中会出现一个持续错误:ERROR TypeError: ctx.amindiDGES is undefined
我的猜测是,应用程序可能会以某种方式尝试在通过服务器获取数据之前显示数据,它会在控制台中给出错误,之后,它会一遍又一遍地发出多个请求,直到 API 被阻塞。
我想知道您在获取数据时是否有这样的问题
【问题讨论】:
-
另外,请分享
daitriecoordinatebi方法的调用位置。由于数据以异步方式到达,因此您应该在表中添加一些条件渲染,例如<table *ngIf="amindiDGES">,它将处理ctx.amindiDGES is undefined错误。 -
我已经包含了代码,在 main.component.ts 中调用了 daitriecoordinatebi。我明白了,所以为了摆脱控制台错误,您需要使用 if 调节,但它隐藏了问题而不是修复它,对吧?或者除非您使用 if 条件,否则通常会使用异步获取控制台错误?
-
您应该将
Observable与async管道一起使用或与*ngIf同步
标签: angular typescript httpclient