Angular 2 - 使用@Input 传递 url
Angular 2 - Passing a url with @Input
我正在为下拉 select 菜单制作一个组件。我希望能够动态加载菜单选项。我最初想通过使用@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
但我收到错误:"Parser Error: Unexpected token / at column 1 in [/api/LogViewer/GetOpts]"。我也试过用“'/api/LogViewer/GetOpts'”来做,但是失败并出现错误 "SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse ()"。将 url 放入父 class 的变量中并绑定到该变量时,我遇到了同样的错误。
这可以吗?还是我应该尝试一种不同的方式来完全实现我的目标?
谢谢!
当您传递静态字符串时,您应该执行以下操作,
<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
});
}
我正在为下拉 select 菜单制作一个组件。我希望能够动态加载菜单选项。我最初想通过使用@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
但我收到错误:"Parser Error: Unexpected token / at column 1 in [/api/LogViewer/GetOpts]"。我也试过用“'/api/LogViewer/GetOpts'”来做,但是失败并出现错误 "SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse ()"。将 url 放入父 class 的变量中并绑定到该变量时,我遇到了同样的错误。
这可以吗?还是我应该尝试一种不同的方式来完全实现我的目标?
谢谢!
当您传递静态字符串时,您应该执行以下操作,
<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
});
}