Search code examples
jqueryangulartypescriptangular-ngselect

Angular 2 - ng-select - get datas from a JSON file


I istalled the ng-select component that allow me to display an autocompleter in an editable select.

I tried to get the options of this select by a JSON but this doesn't work for me!

This work - component:

prodFilterDescr: Array<IOption> = [
        {label: 'Belgium', value: 'Belgium'},
        {label: 'Luxembourg', value: 'Luxembourg'},
        {label: 'Netherlands', value: 'Netherlands'}
    ];

Html:

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

This doesn't work - component (in costructor):

        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) 

Html:

            <ng-select
                    [options]="typeProdFilter"

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

It seems can't read what wrote in costructor or other methods...how can I let my "options" reach my JSON data?


Solution

  • Issue is related to async call of http.get method

    Try to run this code :

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

    For loading options dynamically please checkout this also :

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