我的 Angular 服务中有一个方法,它将一系列字符串组合到一个 URL 中,用于 Google 的 Youtube Data API v3 的 get 请求。
当我最终组合字符串时,其中的一部分被省略(请参见下面日志中的...)。
记录每个值,以及与经典串联和字符串插值结合使用时的结果。两者都省略了我的字符串的一部分,破坏了我的获取请求。
为什么会发生这种情况?我怎样才能防止这种情况发生?
日志
Parts
https://www.googleapis.com/youtube/v3/ search AIzjSyCA_g_zkSTs43Py7yjZtOAcXWvkwQTdU snippet zelda 3 items(id,snippet(title,description))
Concat Combined
https://www.googleapis.com/youtube/v3/search?key=AIzjSyCA_g_zkSTs43Py7yjZtO…art=snippet?q=zelda?maxResults=3?fields=items(id,snippet(title,description))
Interpolation Combined
https://www.googleapis.com/youtube/v3/search?key=AIzjSyCA_g_zkSTs43Py7yjZtO…art=snippet&q=zelda&maxResults=3&fields=items(id,snippet(title,description))
方法
public searchByKeyword(): Observable<any> {
const base = 'https://www.googleapis.com/youtube/v3/';
const endpoint = 'search';
const apiKey = 'AIzjSyCA_g_zkSTs43Py7yjZtOAcXWvkwQTdU';
const part = 'snippet';
const query = 'zelda';
const maxResults = '3';
const fields = 'items(id,snippet(title,description))';
console.log('Parts');
console.log(base, endpoint, apiKey, part, query, maxResults, fields);
const concatCombined = base + endpoint + '?key=' + apiKey + '?part=' + part + '?q=' + query + '?maxResults=' + maxResults + '?fields=' + fields;
console.log('Concat Combined');
console.log(concatCombined);
const interpolationCombined = `${base}${endpoint}?key=${apiKey}?part=${part}&q=${query}&maxResults=${maxResults}&fields=${fields}`;
console.log('Interpolation Combined');
console.log(interpolationCombined);
return this.http.get(interpolationCombined, this.getHeaderOption()).map(x => x.json());
}
请注意,出于安全原因,API key 已被修改。它不起作用。
更新
该错误似乎与浏览器有关。 Edge 不会缩短我的 url,但无法读取我的字段部分的最后两个 ))。
我想这改变了我如何编码/组合我的网址的问题,以便浏览器可以实际组合它并理解整个部分。
最佳答案
您在查询 URL 中使用了太多问号(“?”)。您只需要第一个定义查询参数,然后使用与号(“&”)来限制每个参数。
const concatCombined = base + endpoint + '?key=' + apiKey + '&part=' + part + '&q=' + query + '&maxResults=' + maxResults + '&fields=' + fields;
const interpolationCombined = `${base}${endpoint}?key=${apiKey}&part=${part}&q=${query}&maxResults=${maxResults}&fields=${fields}`;
关于javascript - 为什么我的字符串的一部分被省略了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44524884/