在ng2-select2中使用AJAX

时间:2017-09-05 08:31:41

标签: angularjs ajax jquery-select2 angularjs-select2

我的angular2js项目中有很多下拉列表。我正在使用ng2-select2来获取这些下拉列表。在某些下拉列表中,我需要根据字符串用户类型从API中过滤并获取数据到select2搜索框中。插件初始化但不会触发任何AJAX。

到目前为止我的代码:

HTML:

import { Component,OnInit  } from '@angular/core';
import {Select2OptionData} from 'ng2-select2';
import {AlertService, LTJService} from '../../_services/index';
import { Observable } from 'rxjs/Observable';

@Component({
    selector: 'nationalities',
    templateUrl: '../../views/buyer_profile/nationalities.component.html',
})

export class NationalityComponent implements OnInit {
    //public nationalities: Observable<Array<Select2OptionData>>;
    public options: Select2Options;
    public ajaxOptions: Select2AjaxOptions;


    constructor(private alertService: AlertService, private ltjService: LTJService) {
    }

    ngOnInit(): void {
        console.log('In ngOnInit');

        this.ajaxOptions = {
            url: '<API URL>',
            dataType: 'json',
            delay: 250,
            cache: false,
            data: (params: any) => {
                console.log("AA", params);
                return {
                    query: params.term,
                    gotoPage: params.page
                }
            },
            processResults: (data: any, params: any) => {
                params.page = params.page || 1;
                console.log('data: ', data);
                return {
                    results: $.map(data.data, function(obj) {
                        return {id: obj.id, text: obj.name};
                    }),
                    pagination: {
                        more: (params.page * 10) < data.objectValue.total_count
                    }
                };
            },
        };

        this.options = {
            ajax: this.ajaxOptions
        }
    } 
}

组件:

boot

有人能指出我正确的方向吗? 任何帮助都非常感谢。

1 个答案:

答案 0 :(得分:1)

你使用的数据只输入数据而不是选项

<select2 [data]="options | async"></select2> 

<select2 [options]="options | async"></select2>