我需要将select / option的结果合并到一个变量中(它属于API的URL),并且我是新处理Typescrip的人,所以我遇到了一些错误以及其他我不知道如何处理的内容做。 例如,添加select / option的结果(cat,diff,type旁边的网址),然后将其保存在localStorage中,以将其调用到另一个组件(就像在javascript中一样)
html
<h5>Select Type:</h5>
<form name="formul2" class="cont">
<div class="box">
<select id="type" name="type" [(ngModel)]="typ">
<option value="">Any Type</option>
<option value="&type=multiple">Multple Choice</option>
<option value="&type=boolean">True / False</option>
</select>
</div>
</form>
<a class="btn" id="fetch" href="game">Play</a>
<a class="btn" href="highscores">High Scores</a>
TS
export class IndexComponent implements OnInit {
constructor() { }
ngOnInit() {
}
public diff:string;
public cat:string;
public typ:string;
}
const url:string = 'https://opentdb.com/api.php?amount=20';
var newUrl:string = url + diff + cat + typ;
var x = document.getElementById('fetch')
x.addEventListener('click', function(e) {
localStorage.setItem("urlGame", newUrl);
});
答案 0 :(得分:1)
在选择元素上添加更改侦听器方法
<select id="type" name="type" [(ngModel)]="typ" (chnage)="setChange(typ)">
<option value="">Any Type</option>
<option value="&type=multiple">Multple Choice</option>
<option value="&type=boolean">True / False</option>
</select>
组件
const url: string = 'https://opentdb.com/api.php?amount=20';
export class IndexComponent implements OnInit {
constructor() { }
ngOnInit() {
}
public diff: string;
public cat: string;
public typ: string;
public newUrl: string;
public setChange(selectedValue: any) {
this.newUrl = url + this.diff + this.cat + selectedValue;
localStorage.setItem('urlGame', this.newUrl);
}
}
您可以将“ ngx-webstorage-service”用于本地存储
答案 1 :(得分:0)
如果您不知道数据类型,则可以简单地初始化为任何
public any_variable: any;
尝试一下:
let url:string = "https://www.example.com";
let any_variable:string = `${url}/api/${diff}`;
答案 2 :(得分:0)
我想您要达到的目标是最终URL:
https://opentdb.com/api.php?amount=20/diff/cat/typ
如果是这种情况,则可以使用字符串模板来实现,如下所示:
var newUrl:string = `${this.url}/${this.diff}/${this.cat}/${this.typ}`