0

私のhtmlで私が持っている

typeahead="name for name in search($viewValue)

サーバーから返されたデータは期待どおりです。しかし、これは非同期リクエストであるため、以下のコードの複数の場所で行っているリターンは価値がないことに気付きました.上記のhtmlコードがそれを受け取ることができるようにデータ配列を返していないからです.

        $scope.search = function (term) {
            return $http({
                method: 'GET',
                url: 'rest/search',
                params: {
                    term: term,
                    types: '21'
                }
            }).
            success(function (data, status, headers, config) {
                var Names = [];
                for (var i = 0; i < data.length; i++) {
                    Names.push(data[i].name);
                }
                console.log(Names);//as expected

                return Names;
            }).
            error(function (data, status, headers, config) {
                console.log(status);
            });

        };

typeahead で使用できるように、非同期 HTTP GET 要求からデータを配列形式で返すにはどうすればよいですか。

HTTP GET の成功に関するこの例のようなデータ変数に格納する必要がありますhttps://stackoverflow.com/a/12513509/494461

しかし、どうすれば関数を実行し、配列内のストレージ変数を使用できますか?

typeahead="name for name in search($viewValue)

また

typeahead="name for name in dataStoredInHTTPGetSucess

上記の2つをどうにかして組み合わせることができますか?

4

1 に答える 1

1

これは多かれ少なかれhttps://stackoverflow.com/a/15930592/1418796の複製です。あなたがする必要があるのは、それらの行に沿って、関数からプロミスを返すことです:

$scope.search = function (term) {
        return $http({
            method: 'GET',
            url: 'rest/search',
            params: {
                term: term,
                types: '21'
            }
        }).
        then(function (response) {
            var names = [];
            for (var i = 0; i < response.data.length; i++) {
                names.push(response.data[i].name);
            }
            console.log(names);//as expected

            return names;
        });

    };
于 2013-10-17T16:10:06.597 に答える