【发布时间】:2019-02-19 14:05:58
【问题描述】:
我正在尝试在制作天气应用程序时自学 Angular4。我无法让 API 连接。我已尝试使用以下资源进行允许。
我无法像示例中那样让对象出现在控制台中。我在终端或控制台中没有收到任何错误。我注释掉了我试图让它工作的另一种方式,并删除了示例中的 apikey。这是我的 app.component.ts。除此之外,我在 app.module.ts 中导入了 httpclientmodule。我是初学者,这是我第一次发帖,如果我做错了,我很抱歉。
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import 'rxjs/add/operator/map';
@Component({
selector: "app",
templateUrl: "./app.component.html",
styleUrls: [ "./app.component.css" ]
})
export class AppComponent {
name = "Angular 4 Weather App";
apiKey = "";
private apiUrl = "http://api.openweathermap.org/data/2.5/forecast?q=london&APPID=" + this.apiKey;
data: any = {};
constructor (private http: HttpClient) {
// this.getWeather();
// this.getWeatherData();
}
// getWeather() {
// return this.http.get(this.apiUrl)
// .map((res: Response) => res.json())
// }
// getWeatherData() {
// this.getWeather().subscribe(data => {
// console.log(data);
// this.data = data;
// })
// }
ngOnInit(): void {
this.http.get(this.apiUrl).subscribe(data => {
this.data = data;
console.log(data);
});
}
}
【问题讨论】:
-
在 Chrome 中打开开发者工具面板(按 F12)并转到“网络”选项卡。刷新您的应用程序以重新触发请求并查看来自服务器的实际响应。可能是您从 API 中收到错误消息。代码看起来不错。
-
我相信你不能简单地创建一个名为
ngOnInit的函数并让框架调用它。你的班级需要实现OnInit。在此处查看 peek a boo 组件:angular.io/guide/lifecycle-hooks。最简单的做法是在ngOnInit函数的开头设置一个调试器或console.log,以确保它甚至正在运行。完成这项工作后,请花一些时间查看该页面上的完整钩子列表,以了解您想将哪个钩子用于您的用例。 -
我在网络标签中看不到任何错误。 apiUrl 的状态为 200。此外,在 ngOnInit 开始时尝试了 console.log,但没有成功将 OnInit 添加到类中。但是,在添加/不添加 OnInit 的情况下,执行警报而不是 console.log 都有效。我不确定这是否正常。
标签: angular