javascript - 为什么我的字符串的一部分被省略了?

标签 javascript string angular

我的 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/

相关文章:

arrays - 从字符串数组中过滤掉空字符串

javascript - 提取位于两对特殊字符之间的文本

Angular 2 ng-bootstrap 模态

javascript - Nativescript Angular TabStrip可见性设置为折叠仍然占用空间

javascript - tinymce制表符缩进

javascript - 我的嵌套数组不会在 javascript 中打印

javascript键检测不添加最新字符

typescript - Angular2 嵌套路由不起作用

javascript - 为什么我无法注册回调到 "normal-module-loader"

javascript - 在 Angular JS With Wcf Service 的飞行前响应中,Access-Control-Allow-Methods 不允许方法 PUT