Get an users playlist with Spotify API (how to add

2020-04-21 00:30发布

问题:

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;

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

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

How do you append the auth key to the request to get rid of the error?

Thanks!

回答1:

you can try this code import 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

i hope this will help



回答2:

You may find it helpful if other answers wouldn't work...

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

You can also generate OAuth Token from below link:

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