Angular 2 - ng-select - 从JSON文件中获取数据

时间:2017-07-24 07:21:10

标签: jquery angular typescript angular-ngselect

我是ng-select组件,允许我在可编辑的选择中显示自动完成器。

我尝试通过JSON获取此选项的选项,但这对我不起作用!

这项工作 - 组件:

        ...<ng-select
                [options]="prodFilterDescr"
                placeholder="Prodotto"
        >
        </ng-select>...

HTML:

        this.http.get('app/json/filtriProdotti.json')
        .subscribe(res => this.filters = res.json());
        var filter = [];
        this.filters.forEach(function(item){
            filter.push(item.tipoProdottoId)
        })  
        console.log(filter)   
        let typeProdFilter: Array<IOption> = filter;
        console.log(typeProdFilter) 

这不起作用 - 组件(在costructor中):

            <ng-select
                    [options]="typeProdFilter"

                    placeholder="Tipo prodotto"
            >
            </ng-select>

HTML:

  401:
    body:
      application/json:
        type: t.error-response
        examples:
          invalidcredentials: !include examples/errors/error-response-1.json
          accountlocked: !include examples/errors/error-response-2.json
          accountinactive: !include examples/errors/error-response-3.json

似乎无法读取在costructor或其他方法中写的内容......我怎样才能让我的“选项”达到我的JSON数据?

1 个答案:

答案 0 :(得分:2)

问题与async方法的http.get调用相关

尝试运行此代码:

// define this outside of constructor
typeProdFilter: Array<IOption>;

// keep this inside the constructor
this.http.get('app/json/filtriProdotti.json')
.subscribe(res => 
{
    this.filters = res.json()
    var filter = [];
    this.filters.forEach(function(item){
        filter.push(item.tipoProdottoId)
    })  
    console.log(filter)   
    this.typeProdFilter = filter;
    console.log(this.typeProdFilter)
});

要动态加载选项,请同时查看:

https://basvandenberg.github.io/ng-select/examples/load-options