michaeldd
michaeldd

Reputation: 514

Promise in MagicSuggest data function

I have tried asking this question directly on github but there does not seem to be much movement in this project anymore. It would be great if someone on SO has an idea. Is it possible to return a promise in the data function? I have tried the following and it does not seem to work. The issue is that I am trying to make an ajax call within the data-function, which expects a result/data array. Of course I cannot do this when making an asynchronous ajax call.

var ms = $('#mycombo').magicSuggest({minChars: 2, data : function(q) {
    return someAPI.findSuggestions(q, currentLang).then(function(response) {

        if(!_.isEmpty(response.data.suggestions)) {
            _.each(response.data.suggestions, function(suggestion) {
                if (suggestion.id && suggestion.label) {
                    data.push({ id: suggestion.id, name: suggestion.label });
                }
            });
        }
    });

    return data;
}});

If there is an alternative way of solving this, I would be very grateful for your help.

Thanks in advance.

Michael

Upvotes: 0

Views: 561

Answers (2)

Stevie
Stevie

Reputation: 70

I've also done it this way:

const suggester: any = divElem.magicSuggest({
    ...more properties here...
    data: (query) => {
        if (query) {                    
            this.myService.mySearch(query).take(1).subscribe((list) => {
                suggester.setData(list);
            });
         }
         return [];
    },
    ...more properties here...
});

Where mySearch(query) returns:

Observable<MyObject[]>

Upvotes: 0

michaeldd
michaeldd

Reputation: 514

For those interested, I have managed to find a solution to the problem. As posted on github (https://github.com/nicolasbize/magicsuggest/issues/281) you need to use the keyup event instead of setting the data property during initialization. So it now looks something like this:

var ms = $('#mycombo').magicSuggest({minChars: 2});

$(ms).on('keyup', function(e, m, v) {
    // ... get data via ajax and call "ms.setData(data)" in the response callback ...
    // ... you can use m.getRawValue() to get the current word being typed ...
    ms.setData(data);    
}

This will cause an ajax call to be fired after every key press, so you may want to improve this by adding some kind of a delay or something.

Upvotes: 0

Related Questions