我为下拉选择菜单制作了一个组件。我希望能够动态加载菜单的选项。我最初想通过使用@Input来传递所需控制器方法的url来获取数据。这是我到目前为止(简化):
export class DropdownInput {
// List of options for the dropdown to have
public options: InputOption[];
// Url for controller method to get options
@Input() optionSrc: string;
// Get list of options on construction
constructor(http: Http) {
http.get(this.optionSrc).subscribe(result => {
this.options = result.json();
});
}
}
我试图像这样使用这个下拉组件:
<dropdown-input
[optionSrc]="/api/LogViewer/GetOpts">
</dropdown-input
但我收到错误:&#34;解析器错误:[/ api / LogViewer / GetOpts]&#34;中第1列的意外令牌/。我也试过这样做&#34;&#39; / api / LogViewer / GetOpts&#39;&#34;,但这失败了,错误&#34;语法错误:意外的令牌&lt;在JSON位于JSON.parse()&#34;的位置0。将url放在父类中的变量并绑定到该类时,我得到相同的错误。
这可能吗?或者我应该尝试不同的方式来实现我的目标?
谢谢!
答案 0 :(得分:2)
当您传递静态字符串时,您应该执行以下操作,
<dropdown-input
[optionSrc]="'/api/LogViewer/GetOpts'">
</dropdown-input>
如果构造函数不适合你,那么你应该考虑使用 ngOnInit()
之类的,
ngOnInit() {
http.get(this.optionSrc).subscribe(result => {
this.options = result;
//<<<### changed this line... as suggested by StefanSvrkota
});
}