首页 > 解决方案 > Angular 6 Headers 授权和图表

问题描述

我在 1 中有几个问题。

这是我正在使用的代码:

天气.service.ts:

'
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { map } from 'rxjs/operators';   

let headers: HttpHeaders = new HttpHeaders();
headers = headers.append('Accept', 'application/json');

@Injectable({
  providedIn: 'root'
})


export class WeatherService {


  constructor(private _http: HttpClient) { }

  dailyForcast() {
    return this._http.get('http://history.openweathermap.org/data/2.5/history/city?q=London,UK', {headers})
.pipe(map(result => result));
 }
}
`

然后我有组件:

import { WeatherService } from './../../weather.service';
import { Chart } from 'chart.js';
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-backtesting',
  templateUrl: './backtesting.component.html',
  styleUrls: ['./backtesting.component.css']
})
export class BacktestingComponent implements OnInit {
  LineChart = [];
  constructor( private _weather: WeatherService) { }

  ngOnInit() {
    this._weather.dailyForcast()
    .subscribe(res => {
      console.log(res);
    });
  }

}

然后我们有错误:

ERROR Object { headers: Object, status: 401, statusText: "Unauthorized",   url: "http://history.openweathermap.org/d…", ok: false, name: "HttpErrorResponse", message: "Http failure response for http://hi…", error: Object }

这个错误似乎不合适。在上面的链接中,我们可以毫无问题地提取 json 信息。

这是上述链接的输出。所有这些都是对下一部分的测试,使用 chartjs 绘制这些数据。无需凭据即可查看。我计划使用 2 个 API。1 需要 auth 其他不需要。

{"message":"","cod":"200","city_id":2643743,"calctime":0.0875,"cnt":3,"list":[{"main":{"temp":279.946,"temp_min":279.946,"temp_max":279.946,"pressure":1016.76,"sea_level":1024.45,"grnd_level":1016.76,"humidity":100},"wind":{"speed":4.59,"deg":163.001},"clouds":{"all":92},"weather":[{"id":500,"main":"Rain","description":"light rain","icon":"10n"}],"rain":{"3h":2.69},"dt":1485717216},{"main":{"temp":282.597,"temp_min":282.597,"temp_max":282.597,"pressure":1012.12,"sea_level":1019.71,"grnd_level":1012.12,"humidity":98},"wind":{"speed":4.04,"deg":226},"clouds":{"all":92},"weather":[{"id":500,"main":"Rain","description":"light rain","icon":"10n"}],"rain":{"3h":0.405},"dt":1485745061},{"main":{"temp":279.38,"pressure":1011,"humidity":93,"temp_min":278.15,"temp_max":280.15},"wind":{"speed":2.6,"deg":30},"clouds":{"all":90},"weather":[{"id":701,"main":"Mist","description":"mist","icon":"50d"},{"id":741,"main":"Fog","description":"fog","icon":"50d"}],"dt":1485768552}]}

我希望了解为什么会发生此错误以及解决方法是什么。我还在寻找有关 chartjs 的资源并使用 Angular 6 中的服务调用 API。我已经完成了许多教程,但所有教程似乎都没有我的解决方案。

先感谢您!

标签: angularchart.jsmean-stack

解决方案


推荐阅读