问题描述
我正在用本教程研究有关构建12个不同的angular 2应用程序的详细信息,其中其中一个可以与Spotify Web API一起使用,并且我要为其添加更多功能;
I'm doing this course in udemy about building 12 different angular 2 apps, and one of them works with Spotify Web API and I'm adding more features to it;
我已经学习了如何处理简单的GET请求
I've learn how to work with simple GET request like
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());
}
该功能不需要身份验证密钥
That function requires no auth key
但是要获取播放列表,我需要传递身份验证密钥请求,否则我会收到错误消息,而不是Json格式的播放列表
But to get a playlist I need to pass an auth key to the request, otherwise I get an error instead of a Json formatted playlist
如何将auth密钥附加到请求中以消除错误?
How do you append the auth key to the request to get rid of the error?
谢谢!
推荐答案
您可以尝试以下代码导入该文件
you can try this codeimport this file
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());
}
有关更多信息,请检查这些链接
for more information check these links
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());
}
}
如果上述方法不起作用,请尝试
try this if above not work
我希望这会有所帮助
这篇关于使用Spotify API获取用户播放列表(如何在http请求angular 2中添加访问令牌?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!