【问题标题】:401 Error While Accessing Youtube API From Angular Component从 Angular 组件访问 Youtube API 时出现 401 错误
【发布时间】:2019-11-15 18:43:04
【问题描述】:

我正在开发一个 Angular 应用程序,我在其中使用 YouTube API 获取 Youtube 视频列表。下面是我为使用 API 而创建的服务。

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

@Injectable({
  providedIn: 'root'
})
export class YoutubeService {

    apiKey = 'AIzaSyD-Eq2cgbt3jBLTC1IORwVh8_ebSAlPnYcZ';

    constructor(private http: HttpClient) {
    }

    getMessage(): string {
        return 'Hello World!';
    }

    getVideosForChannel(channel: string, maxResults: number): Observable<object> {
        const url = 'https://www.googleapis.com/youtube/v3/search?key=' + this.apiKey +
            '&channelId=' + channel + '&order=date&part=snippet &type=video,id&maxResults=' + maxResults;
        return this.http.get(url)
          .pipe(map((res) => {
            return res;
          }));
    }
}

为了在组件上显示视频列表,我使用以下代码

this.youtubeService.getVideosForChannel('UCl7379cd3Pv81tySqs0TR7A', 10)
      .subscribe(list => {
        for (let item of list['items']) {
          console.log(item);
          this.videos.push(item);
        }
      });

问题是我收到以下错误消息:

HttpErrorResponse {headers: HttpHeaders, status: 401, statusText: "OK", url: "https://www.googleapis.com/youtube/v3/search?key=A…=date&part=snippet%20&type=video,id&maxResults=10", ok: false, …}

有人可以帮我解决这个错误吗?谢谢

【问题讨论】:

    标签: angular youtube-api youtube-data-api angular8


    【解决方案1】:

    尝试将请求link放入浏览器并检查输出,如果遇到错误请求等错误,则需要确保传递的密钥有效且没有多余的空格和不超过一天内每个密钥的最大请求数限制。

    【讨论】:

    • 我已经尝试过了,当我将请求的链接放入浏览器时,我没有收到任何错误。
    • 所以你已经收到了预期的输出,对吗?
    • 是的,我收到了预期的输出
    猜你喜欢
    • 2012-05-12
    • 1970-01-01
    • 2016-03-18
    • 1970-01-01
    • 2021-04-06
    • 1970-01-01
    • 1970-01-01
    • 2020-09-18
    • 1970-01-01
    相关资源
    最近更新 更多