【发布时间】:2020-06-04 07:03:56
【问题描述】:
我在名为 getWeather 的服务中有一个方法。它联系具有给定经度和纬度的 API 并返回响应:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class OpenWeatherService {
constructor(private http: HttpClient) { }
getWeather(lat, long) {
return this.http.get("http://api.openweathermap.org/data/2.5/weather?lat=" + lat + "&lon=" + long + "&appid=hiddenappid");
}
}
我在一个组件中使用它,该组件根据它返回的信息进行一些计算。我试图将它发回的信息存储在一个名为“weatherData”的属性中,但由于 http.get 方法是异步的,它让未定义的 weatherData 属性首先打印到控制台。我该如何解决这个问题?这是组件:
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder } from '@angular/forms';
import { OpenWeatherService } from '../open-weather.service';
@Component({
selector: 'app-weather',
templateUrl: './weather.component.html',
styleUrls: ['./weather.component.css']
})
export class WeatherComponent implements OnInit {
public weatherSearchForm: FormGroup;
public weatherData: any;
constructor(private formBuilder: FormBuilder, private OpenWeatherService: OpenWeatherService) { }
ngOnInit() {
this.weatherSearchForm = this.formBuilder.group({
longitude: [''],
latitude: ['']
})
}
sendToOpenWeather(formValues) {
this.OpenWeatherService
.getWeather(formValues.longitude, formValues.latitude)
.subscribe(data => {
this.weatherData = data;
// prints the correct longitude and latitude
console.log(this.weatherData);
});
// prints undefined
console.log(this.weatherData);
}
}
【问题讨论】:
-
您无法从异步函数外部获取数据。您需要在订阅中完成您的流程。你想用数据做什么?
-
@pc_coder 我想获取天气,然后将用户界面基于它。根据从 api 返回的天气进行计算。有点像,如果(天气是某个温度){用户界面看起来像这样}。但是除了这个愚蠢的程序之外,假设我想从 API 中获取数据并将其粘贴到一个属性中,然后将该属性用于其他用途,我该怎么做呢?
-
编写一个函数,该函数将参数作为 api 响应的结果,而不是你的函数在其中插入,然后在订阅中调用你的函数
标签: angular asynchronous