Angular 8: ERROR TypeError: Cannot read property 'toLowerCase' of undefined
Angular 8: ERROR TypeError: Cannot read property 'toLowerCase' of undefined
每次我尝试在浏览器中记录 api 结果时,我都收到错误类型错误:无法读取未定义的 属性 'toLowerCase'。
这是我的服务 class
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。我刚刚开始学习 angular 并尝试将我迄今为止获得的知识应用到这个迷你项目中。
编辑:将空字符串分配给 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, …}
。
在调用天气和位置 url 之前,能否请您检查属性 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);
}
似乎您还需要一个访问密钥来访问 url 中提到的 api 天气和位置 [myKey]
还可以尝试通过直接在导航器上使用(lat、long 和 key)的真实值测试它们来测试天气和位置 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
的基本承诺。
这是一个工作示例:
GetLocation Service
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);
}
}
Component 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()
}
}
希望对您有所帮助!
每次我尝试在浏览器中记录 api 结果时,我都收到错误类型错误:无法读取未定义的 属性 'toLowerCase'。 这是我的服务 class
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。我刚刚开始学习 angular 并尝试将我迄今为止获得的知识应用到这个迷你项目中。
编辑:将空字符串分配给 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, …}
。
在调用天气和位置 url 之前,能否请您检查属性 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);
}
似乎您还需要一个访问密钥来访问 url 中提到的 api 天气和位置 [myKey]
还可以尝试通过直接在导航器上使用(lat、long 和 key)的真实值测试它们来测试天气和位置 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
的基本承诺。
这是一个工作示例:
GetLocation Service
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);
}
}
Component 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()
}
}
希望对您有所帮助!