我正在为下拉选择菜单制作一个组件。我希望能够动态加载菜单选项。我最初考虑通过使用 @Input 传入所需 Controller 方法的 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
但我收到错误:“解析器错误:意外的标记/位于 [/api/LogViewer/GetOpts] 中的第 1 列”。我也尝试将其作为“'/api/LogViewer/GetOpts'”进行操作,但这失败并出现错误“SyntaxError: Unexpected token < in JSON atposition 0 at JSON.parse ()”。将 url 放入父类的变量中并绑定(bind)到该变量时,我遇到了同样的错误。
这可以做到吗?或者我应该尝试一种不同的方式来完全实现我的目标?
谢谢!
最佳答案
当您传递静态字符串时,您应该执行以下操作,
<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
});
}
关于Angular 2 - 使用 @Input 传递 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40182904/