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

时间:2017-01-26 17:14:12

标签: angular spotify

我正在为udemy做这个关于构建12个不同的角度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我需要将auth密钥传递给请求,否则我会收到错误而不是Json格式的播放列表

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

谢谢!

2 个答案:

答案 0 :(得分:2)

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

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());
  }
}

如果上面没有工作,试试这个

我希望这会有所帮助

答案 1 :(得分:0)

如果其他答案不起作用,您可能会觉得有用......

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令牌:

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