Aaron
Aaron

Reputation: 1061

Make GET call to REST service with parameters in Angular 2

I am trying to make a GET call to the YouTube Web API but I cannot figure out how to pass parameters using the http.get function. I have used fiddler and made sure the request is being made. I am currently getting a 400 error saying that I am missing a the parameter "Part". How can I modify my code to include the required parameters in my request?

private _url = 'https://www.googleapis.com/youtube/v3/';
private _key = '';

getPlaylistVideos(playlistId, pageToken){

    var url = this._url + "playlistItems";
    var options =  { part: 'snippet', maxResults: 50, playlistId: playlistId, key: this._key, pageToken: pageToken }

    return this.http.get(url, options);

}

Upvotes: 2

Views: 3944

Answers (2)

Filip Lauc
Filip Lauc

Reputation: 3029

You need to include the search params in to your request. I think this will work for you:

getPlaylistVideos(playlistId, pageToken) {
    let url = `${this._url}playlistItems`,
        options =  { part: 'snippet', maxResults: 50, playlistId: playlistId, key: this._key, pageToken: pageToken }, 
        params = URLSearchParams();

    for (let key in options) params.set(key, options[key);

    return this.http.get(url, {search: options});
}

You create the URLSearchParams using the set method you can find the full documentation here

Upvotes: 2

daan.desmedt
daan.desmedt

Reputation: 3820

Please have a look at the already asked & solved question regarding AngularJS & YouTube V3 API. See here thanks to @Sandeep Sukhija.

Anyhow, about the missing parameter part, add it to the request ex: part: 'snippet'

Example code :

function getPlaylistVideos(playlistId, pageToken) {
    // pass the page token as a parameter to the API
    $.get('https://www.googleapis.com/youtube/v3/playlistItems', { part: 'snippet', maxResults: 50, playlistId: playlistId, key: key, pageToken: pageToken })
}

How to use the part parameter

The part parameter is a required parameter for any API request that retrieves or returns a resource. The parameter identifies one or more top-level (non-nested) resource properties that should be included in an API response. For example, a video resource has the following parts:

snippet contentDetails fileDetails player processingDetails recordingDetails statistics status suggestions topicDetails

Upvotes: 0

Related Questions