【问题标题】:Angular 2 - Passing a url with @InputAngular 2 - 使用 @Input 传递 url
【发布时间】:2016-10-22 02:22:49
【问题描述】:

我正在为下拉选择菜单制作一个组件。我希望能够动态加载菜单的选项。我最初是想通过使用@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

但我收到错误消息:“解析器错误:在 [/api/LogViewer/GetOpts] 的第 1 列出现意外的令牌/”。我也尝试将其作为“'/api/LogViewer/GetOpts'”执行,但失败并出现错误“SyntaxError: Unexpected token

这可能吗?还是我应该尝试另一种方式来完全实现我的目标?

谢谢!

【问题讨论】:

    标签: angular angular2-template


    【解决方案1】:

    当你传递一个静态字符串时,你应该遵循,

    <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
            });
    }
    

    【讨论】:

    • 我事先尝试过不带空格的方法,现在只带空格,不幸的是我仍然收到错误消息:“SyntaxError: Unexpected token )”。 来自哪里,是因为我订阅了这个 http.get 的结果吗?
    • @csy9 我相信您会收到错误消息,因为您试图将result 解析为 json,而实际上它不是 json。尝试使用this.options = result; 并让我们知道它是否有效。或者只是 console.log(result); 看看你会得到什么。
    • @StefanSvrkota 你得到了一个点。
    • @StefanSvrkota 好电话。通过将“this.options = result.json()”替换为“console.log(result)”,我可以看到我正在返回一些随机的 html 垃圾,并且 xhr 网络调用为 null 而不是有效的控制器。
    • @StefanSvrkota micronyks 的编辑基本上解决了它。构造函数刚刚设置了 http 服务,然后 ngOnInit 进行了调用。我认为发生的事情是我在 http.get 请求之后放置了“console.log(this.optionSrc)”,并且 optionSrc 在构造函数的中途被初始化,所以它在获取期间未定义,但后来似乎没问题.
    猜你喜欢
    • 1970-01-01
    • 2017-01-02
    • 2017-02-12
    • 2017-03-03
    • 2016-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-09
    相关资源
    最近更新 更多