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

Angular 使用Spotify API获取用户播放列表(如何在http请求2中添加访问令牌?),angular,spotify,Angular,Spotify,我正在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+'

我正在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());
}
该函数不需要身份验证密钥

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

如何将身份验证密钥附加到请求以消除错误

谢谢

您可以尝试此代码 导入此文件

从'@angular/Http'导入{Http,Response,Headers,RequestOptions};
searchMusic(str:string,type='artist'){
let headers=new headers({'Content Type':'application/json'},{'Authorization:'add_your_token_here'});/…将内容类型设置为json
let options=newrequestoptions({headers:headers});//创建请求选项
此.searchUrl='0https://api.spotify.com/v1/search?query=“+str+”&offset=0&limit=20&type=“+type+”&market=US”;
返回此。\u http.get(this.searchUrl,选项)
.map(res=>res.json());
}
有关更多信息,请查看这些链接

从'@angular/core'导入{Injectable};
从'@angular/Http'导入{Http,Headers};
@可注射()
出口级PFS服务{
构造函数(私有http:http){}
getProfile(){
let headers=新的headers();
headers.append('Content-Type','application/json');
让authToken=localStorage.getItem('auth_-token');
append('Authorization','Bearer${authToken}');
返回此文件。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令牌:


我尝试了此操作,但出现了一个错误@GerardoSabetta你最终解决了这个问题吗?