Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/url/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 角度8:错误类型错误:无法读取属性';toLowerCase';未定义的_Angular_Api_Geolocation_Observable_Angular8 - Fatal编程技术网

Angular 角度8:错误类型错误:无法读取属性';toLowerCase';未定义的

Angular 角度8:错误类型错误:无法读取属性';toLowerCase';未定义的,angular,api,geolocation,observable,angular8,Angular,Api,Geolocation,Observable,Angular8,我遇到错误TypeError:每次尝试在浏览器中记录api结果时,都无法读取undefined的属性“toLowerCase”。 这是我的服务课 从'@angular/core'导入{Injectable}; 从'@angular/common/http'导入{HttpClient}; @注射的({ providedIn:'根' }) 导出类GetlocationService{ lat:any=''; 长:任意=“”; url:any=''; weatherUrl:any=''; 构造函数(专

我遇到错误TypeError:每次尝试在浏览器中记录api结果时,都无法读取undefined的属性“toLowerCase”。 这是我的服务课

从'@angular/core'导入{Injectable};
从'@angular/common/http'导入{HttpClient};
@注射的({
providedIn:'根'
})
导出类GetlocationService{
lat:any='';
长:任意=“”;
url:any='';
weatherUrl:any='';
构造函数(专用http:HttpClient){
if(导航器.地理位置)
{
navigator.geolocation.getCurrentPosition(位置=>
{
this.lat=position.coords.lation;
this.long=position.coords.longitude;
这个网址=`https://us1.locationiq.com/v1/reverse.php?key=[mykey]&lat=${this.lat}&lon=${this.long}&format=json`;
这是weatherUrl=`https://cors-anywhere.herokuapp.com/https://api.darksky.net/forecast/[mykey]/${this.lat},${this.long}`;
})
}
}
公共getLocationName()
{
返回this.http.get(this.url);
}
公众天气
{
返回this.http.get(this.weatherUrl);
}
}
这是我调用服务的
locationweather
组件

从'@angular/core'导入{Component,OnInit};
从“../getlocation.service”导入{GetlocationService};
从“@angular/common”导入{getLocaleDataFormat};
@组成部分({
选择器:“应用程序位置天气”,
templateUrl:'./locationweather.component.html',
样式URL:['./locationweather.component.css']
})
导出类LocationweatherComponent实现OnInit{
构造函数(私有getLocation:GetlocationService){}
地点:任何=[];
天气:任何=[];
getLocationDetail()
{
this.getLocation.getLocationName().subscribe((数据:any)=>
{
console.log(数据)
此。位置。推送(数据);
})
}
getWeatherDetails()
{
this.getLocation.getWeather().subscribe((weather:any)=>
{
控制台日志(天气)
这个。天气。推(天气)
})
}
焦点清除(添加)
{
附加值=”;
}
恩戈尼尼特(){
//这是.getLocationDetail();
这是getWeatherDetails()
}
}
有人能帮我吗?我正在调用
ngOnit
中的服务,因为每当我的页面加载时,我都需要它们

另外,我刚开始学习angular,并试图将我迄今为止学到的知识应用到这个小型项目中


编辑:将空字符串分配给long、lat、url和weatherUrl之后,我再也看不到控制台中未定义的
Angular 8:ERROR-TypeError:Cannot read属性“toLowerCase”。现在我得到了
ERROR-HttpErrorResponse{headers:HttpHeaders,状态:200,状态文本:“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]

还可以尝试在导航器上直接测试天气和位置URL,并使用实际值(lat、long和key)确保它们是正确的

编辑:

调用
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服务


希望有帮助

在哪里使用“toLowerCase”?尝试为
lat:any输入初始值;长:任何;网址:任何;weatherUrl:任何
,使用它们时URL似乎未定义。您确定
weatherUrl
正确吗?您是否仔细检查了它提供的端点?我在浏览器控制台中看到了错误。现在,将空字符串分配给lat、long、url和weatherUrl之后。我在控制台中看到这个错误。core.js:7187 ERROR HttpErrorResponse{headers:HttpHeaders,status:200,statusText:“OK”,url:“OK:false,…}是的,我的结束点是正确的谢谢你的回答。我按照你的要求做了,我记录了所有变量,没有一个显示出来。浏览器控制台仅显示行号和文件名的空白输出。似乎我的getLocationName和getWeather方法无法读取构造函数中定义的变量。请您更正声明它们的方式,以便我可以在定义的方法中读取它们的值。另外,硬编码的api url工作正常。您能否检查调用getCurrentPosition方法时是否出现错误?我用要添加的代码更新了答案以捕获错误。我没有收到任何错误。我可以从
navigator.geolocation.getCurrentPosition
控制台记录变量值。只是它们可以在getLocationName和getWeather方法中访问。@Rahusinghal我更新了我的答案,请查看第二个编辑部分,并告诉我它是否适合您。
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);
  }
}
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()

  }
}