【问题标题】:Angular4 connecting weather APIAngular4 连接天气 API
【发布时间】:2019-02-19 14:05:58
【问题描述】:

我正在尝试在制作天气应用程序时自学 Angular4。我无法让 API 连接。我已尝试使用以下资源进行允许。

https://medium.com/craft-academy/connecting-an-api-to-an-angular-4-front-end-application-e0fc9ea33202

https://medium.com/codingthesmartway-com-blog/angular-4-3-httpclient-accessing-rest-web-services-with-angular-2305b8fd654b

我无法像示例中那样让对象出现在控制台中。我在终端或控制台中没有收到任何错误。我注释掉了我试图让它工作的另一种方式,并删除了示例中的 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


【解决方案1】:

不要因为是新手而道歉,你会学得很快!

您要做的是创建一个 TypeScript 服务,用于调用天气 API 以取回数据。然后,您将从您拥有的任何组件(当前为 AppComponent)中调用它。您可以通过这种方式更好地分离逻辑和服务器调用。

当您执行服务设置时,请尝试这样的操作。

import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/share';

@Injectable()
export class WeatherService {

    $result: Observable<any>;
    weather: any;

    loadWeather() {  
        $result = this.http.get(this.apiUrl)
            .map(response => { return response["data"] });
            .share();
    }

    this.$result.subscribe(weather => {
        this.weather = weather;
    });

    return this.$result;
}

仅供参考,从服务器映射回响应可能会有所不同,具体取决于您返回的响应。

您可以从这里引用 TS 服务中的 $result 可观察对象,并从中获取任何数据并将其放入天气对象中。您不需要静态定义任何对象来保存数据,您现在可以抓取对象中的任何内容,无论它是否发生变化。

如果您还没有,我强烈建议您阅读本教程,它对我很有帮助:https://angular.io/tutorial

然后您的 AppComponent 可以调用 TS 服务,特别是该方法,以取回数据。然后您可以订阅它,它会在收到数据时执行您的逻辑。

应用组件:

export class AppComponent implements OnInit {

    constructor(
        public weatherService: WeatherService){}

    ngOnInit() {
        this.weatherService.loadWeather().subscribe(weather => {
             ...Do Logic Here....
             todaysTemp = weather.todaysTemp;
        });
    }
}

【讨论】:

  • 我尝试关注angular.io/guide/http 来设置服务,但遇到了一些错误。我认为这将是最好的方法,因为我有一个天气和搜索组件都需要访问。我想我开始在应用程序组件中执行此操作,以查看是否可以首先从 API 获取数据,这也是我提供的初始链接设置它的方式。在尝试其他任何事情之前,我可能应该先阅读该教程。谢谢!
  • 没问题!希望有帮助。该教程帮助了我很多,希望你也觉得它有用!
猜你喜欢
  • 1970-01-01
  • 2020-08-15
  • 2021-07-07
  • 1970-01-01
  • 1970-01-01
  • 2011-12-09
  • 2013-07-06
  • 2019-05-28
  • 1970-01-01
相关资源
最近更新 更多