我试图从同一组件中的另一个函数调用一个函数,但另一个函数不返回任何响应,其他函数调用get call。我不知道如何使用then和promise关键字来等待响应。
请告诉我哪里出错了。
我尝试了其他方法通过navigator函数获取坐标,但它不返回坐标,但当我尝试在浏览器控制台中运行相同的代码时,它返回坐标。
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { map, ignoreElements } from 'rxjs/operators'
import { catchError } from 'rxjs/operators'
import { throwError } from 'rxjs/index'
import { TouchSequence } from 'selenium-webdriver';
import { ThrowStmt } from '@angular/compiler';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = 'Weather';
cityName:string = 'delhi';
backgroundImageUrl:string = '';
weatherDetails:object = {};
iconImageUrl:string= '';
dataSource:any = {};
latitude:number;
longitude: number;
constructor(private http: HttpClient){
}
getUserLocation(): any {
var obj: object = {};
navigator.geolocation.getCurrentPosition(locationSuccess, locationError);
function locationSuccess(position) {
console.log("success");
console.log(position.coords);
obj = position.coords;
}
function locationError() {
console.log("error")
}
return obj;
}
searchCity(){
var coords = this.getUserLocation();
if(coords){
this.http.get('https://api.openweathermap.org/data/2.5/weather?lat='+coords.latitude+'&lon='+coords.longitude+'&mode=json&appid=')
.subscribe(
((response: any) => {
this.dataSource = response;
if(this.dataSource.weather.length > 0){
this.weatherDetails = this.dataSource.weather.filter(function(el){return el})[0];
this.switchBackground();
}
}),
catchError((error) => {
return throwError(error);
})
)
}
}
private switchBackground(){
var weatherId = this.weatherDetails[0].id;
switch(weatherId){
case 711:
this.backgroundImageUrl = '../assets/images/01-smoke.png';
this.iconImageUrl = '';
break;
case 701:
this.backgroundImageUrl = '../assets/images/02-mist.jpg';
this.iconImageUrl = '../assets/images/icons/01-cloudy-sky.png';
break;
default :
break;
}
}
// public getLocation(){
// let promise = new Promise(function(resolve, reject) {
// resolve('resolved');
// reject(new Error("Unable to process your request.")); // ignored
// });
// promise.then(function(response){
// this.searchCity();
// })
// }
ngOnInit(){
this.getUserLocation();
}
}
我希望用相同的坐标得到http.get调用,但实际上它的坐标是未定义的。你能帮我一下吗?
谢谢你事先的帮助。