首页 > 解决方案 > Angular4 连接天气 API

问题描述

我正在尝试在制作天气应用程序时自学 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);
        });
    }

}

标签: angular

解决方案


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

您要做的是创建一个 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;
        });
    }
}

推荐阅读