使用 Spotify API 获取用户播放列表(如何在 http 请求 angular 2 中添加访问令牌?)

Get an users playlist with Spotify API (how to add access token in http request angular 2?)

我正在 udemy 上这门课程,关于构建 12 个不同的 angular 2 个应用程序,其中一个与 Spotify Web API 一起使用,我正在向它添加更多功能;

我已经学会了如何处理简单的 GET 请求,例如

searchMusic(str:string, type='artist'){
    this.searchUrl = 'https://api.spotify.com/v1/search?query='+str+'&offset=0&limit=20&type='+type+'&market=US';
    return this._http.get(this.searchUrl)
        .map(res => res.json());
}

该功能不需要授权密钥

但是对于 get a playlist 我需要向请求传递一个授权密钥,否则我会得到一个错误而不是 Json 格式的播放列表

如何将授权密钥附加到请求以消除错误?

谢谢!

你可以试试这个代码 导入此文件

import { Http, Response, Headers, RequestOptions } from '@angular/http';

   searchMusic(str:string, type='artist'){
        let headers = new Headers({ 'Content-Type': 'application/json' },{'Authorization:'add_your_token_here'}); // ... Set content type to JSON
        let options = new RequestOptions({ headers: headers }); // Create a request option
        this.searchUrl = 'https://api.spotify.com/v1/search?query='+str+'&offset=0&limit=20&type='+type+'&market=US';
        return this._http.get(this.searchUrl, options)
            .map(res => res.json());
         }

有关更多信息,请查看这些链接

https://scotch.io/tutorials/angular-2-http-requests-with-observables https://angular.io/docs/ts/latest/guide/server-communication.html#!#override-default-request-options

import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';

@Injectable()
export class PfService {
  constructor(private http: Http) {}

  getProfile() {
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');
    let authToken = localStorage.getItem('auth_token');
    headers.append('Authorization', `Bearer ${authToken}`);

    return this.http
      .get('/profile', { headers })
      .map(res => res.json());
  }
}

如果上述方法不起作用,请尝试此操作

我希望这会有所帮助

如果其他答案不起作用,您可能会发现它有帮助...

import {Injectable} from '@angular/core';
import {Http, Headers} from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()

export class SearchService {
  private searchUrl: string;

  constructor (private _http: Http) {

  }

  searchMusic(str:string, type='artist'){
      let headers = new Headers();
      let authToken = 'Your OAuth Token Goes Here';
      headers.append('Authorization', 'Bearer '+authToken);
      this.searchUrl = 'https://api.spotify.com/v1/search?q='+str+'&offset=0&limit=20&type='+type+'&market=US';
      return this._http.get(this.searchUrl, { headers })
        .map(res => res.json());
  }
}

您还可以从下面生成 OAuth 令牌 link:

https://developer.spotify.com/web-api/console/get-search-item/