首页 > 解决方案 > Angular 7:检测位置时出现 405 错误

问题描述

检测位置时出现错误 405(不允许方法)。

服务

  public fetchWeatherDataByCoordinates(coordinates: ICoordinates): void {
    console.log("problem here")
    this.selectedLocationId.next(this.currentCoordinatesLocationId);
    if (coordinates) {
      const config = {
        url: this.getWeatherApiUrlByCoordinates(coordinates),
        byCoordinates: true
      };

      this.getWeatherDataByUrl(config);
    }
  }

此代码添加相同的文件服务

 private getWeatherApiUrlByCoordinates(coordinates: ICoordinates): string {
    const { lat, lon } = coordinates;
    const { weatherUrl } = environment;
    const { appid } = constants;
    return `${weatherUrl}?lat=${lat}&lon=${lon}&appid=${appid}`;
  }

编辑添加getWeatherDataByUrl

private getWeatherDataByUrl(config: any): void {
    this.transportService.get(config)
    .pipe(
      filter((res: HttpResponse<any>) => !!res.body),
      map((res: HttpResponse<any>) => <IWeatherData> res.body)
    )
    .subscribe((weatherData: IWeatherData) => {
      if (config.byCoordinates) {
        if (this.currentCoordinatesLocationId === -1) {
          this.selectedLocationId.next(weatherData.id);
        }
        this.currentCoordinatesLocationId = weatherData.id;
      }
      this.patchCurrentWeatherData(weatherData);
    });
  }

运输服务

 public get(config: any): Observable<HttpEvent<any>> {
    const request: HttpRequest<any> = new HttpRequest<any>('GET', config.url, config.body);
    return this.http.request(request);
  }

标签: angulartypescript

解决方案


在您发布的代码片段中,我看不到您使用的是哪种 HTTP 方法,但HTTP 405您看到的意味着您正在发送一个 HTTP 请求,其中包含服务器不期望的方法( GET, POST, PUT, , ...)。DELETE

例如,如果您GET向期望接收POST.

检查那个方法getWeatherDataByUrl,似乎有调用的地方HttpClient


推荐阅读