我遇到错误TypeError:每次尝试在浏览器中记录api结果时,无法读取未定义的属性“ toLowerCase”。 这是我的服务班
import { Injectable } from '@angular/core';
import {HttpClient} from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class GetlocationService {
lat:any='';
long:any='';
url:any='';
weatherUrl:any='';
constructor(private http:HttpClient) {
if(navigator.geolocation)
{
navigator.geolocation.getCurrentPosition( position=>
{
this.lat = position.coords.latitude;
this.long = position.coords.longitude;
this.url =`https://us1.locationiq.com/v1/reverse.php?key=[mykey]&lat=${this.lat}&lon=${this.long}&format=json`;
this.weatherUrl=`https://cors-anywhere.herokuapp.com/https://api.darksky.net/forecast/[mykey]/${this.lat},${this.long}`;
})
}
}
public getLocationName()
{
return this.http.get(this.url);
}
public getWeather()
{
return this.http.get(this.weatherUrl);
}
}
这是我调用服务的locationweather
组件。
import { Component, OnInit } from '@angular/core';
import { GetlocationService } from '../getlocation.service';
import { getLocaleDateFormat } from '@angular/common';
@Component({
selector: 'app-locationweather',
templateUrl: './locationweather.component.html',
styleUrls: ['./locationweather.component.css']
})
export class LocationweatherComponent implements OnInit {
constructor( private getLocation:GetlocationService) { }
locations:any=[];
weathers:any=[];
getLocationDetail()
{
this.getLocation.getLocationName().subscribe((data:any)=>
{
console.log(data)
this.locations.push(data);
})
}
getWeatherDetails()
{
this.getLocation.getWeather().subscribe((weather:any)=>
{
console.log(weather)
this.weathers.push(weather)
})
}
focusClear(add)
{
add.value="";
}
ngOnInit() {
// this.getLocationDetail();
this.getWeatherDetails()
}
}
有人可以帮助我吗?我之所以在ngOnit
中呼叫服务,是因为每当页面加载时都需要它们。
PS。我刚刚开始学习角度知识,并尝试将我到目前为止在这个小型项目中获得的知识运用到这个领域。
编辑:在将空字符串分配给long,lat,url和weatherUrl之后,我再也看不到控制台中的Angular 8: ERROR TypeError: Cannot read property 'toLowerCase' of undefined
。现在,控制台中显示ERROR HttpErrorResponse {headers: HttpHeaders, status: 200, statusText: "OK", url: "http://localhost:4200/", ok: false, …}
。
答案 0 :(得分:0)
您能否在调用天气和位置网址之前检查this.lat和this.long属性的值?通过在控制台中打印它们。
public getLocationName() {
console.log(this.lat);
console.log(this.long);
return this.http.get(this.url);
}
public getWeather() {
return this.http.get(this.weatherUrl);
}
似乎您还需要访问密钥来访问apis [myKey]
中提到的apis天气和位置还可以通过在导航器上直接测试天气和位置url来测试其真实性(纬度,经度和键值),以确保其正确。
修改:
您能否通过捕获以下代码中提到的错误来检查调用navigator.geolocation.getCurrentPosition
方法时是否出错:
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(position => {
console.log('here');
this.lat = position.coords.latitude;
this.long = position.coords.longitude;
},
error => {
console.log('-----------------ERROR:--------------');
console.log(error);
}
);
}
第二次修改:
知道了,navigator.geolocation.getCurrentPosition
需要先完成,然后再调用两个方法getLocationName和getWeather,这两个方法取决于前一个方法的输出。因此,您需要做的就是等待异步方法完成,并在async/await
中使用基本的Promise。
这是一个工作示例:
GetLocation服务
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class GetlocationService {
private lat: any = '';
private long: any = '';
url: any = '';
weatherUrl: any = '';
constructor(private http: HttpClient) {
}
public async initialize() {
await this.getPosition().then(pos => {
this.lat = pos.lat;
this.long = pos.lng;
console.log(`Positon: ${pos.lng} ${pos.lat}`);
});
}
public getPosition(): Promise<any> {
return new Promise((resolve, reject) => {
navigator.geolocation.getCurrentPosition(resp => {
resolve({ lng: resp.coords.longitude, lat: resp.coords.latitude });
},
err => {
reject(err);
});
});
}
public getLocationName() {
console.log('location method :' + this.lat);
console.log('location method:' + this.long);
this.url = ''; //update url
return this.http.get(this.url);
}
public getWeather() {
console.log('weather method:' + this.lat);
console.log('weather method:' + this.long);
this.weatherUrl = ''; //update weather url
return this.http.get(this.weatherUrl);
}
}
组件TS
import { Component, OnInit } from '@angular/core';
import { GetlocationService } from './location.service';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
constructor(private getLocation: GetlocationService) { }
locations: any = [];
weathers: any = [];
getLocationDetail() {
this.getLocation.getLocationName().subscribe((data: any) => {
console.log(data)
this.locations.push(data);
})
}
getWeatherDetails() {
this.getLocation.getWeather().subscribe((weather: any) => {
console.log(weather)
this.weathers.push(weather)
})
}
focusClear(add) {
add.value = "";
}
async ngOnInit() {
await this.getLocation.initialize();
this.getLocationDetail();
this.getWeatherDetails()
}
}
希望有帮助!