Share async data between controllers without making multiple requests

后端 未结 4 1238
盖世英雄少女心
盖世英雄少女心 2021-02-14 20:21

I\'m trying to make a single $http request to get one of my JSON files and use the data across all my controllers.

I saw on egghead.io how to share data acr

4条回答
  •  面向向阳花
    2021-02-14 20:32

    My issue was that I didn't want to wait for resolve before loading another controller because it would show a "lag" between controllers if the network is slow. My working solution is passing a promise between controllers via ui-router's params and the data from promise can be loaded asynchronously in the second controller as such:

    app.route.js - setting the available params to be passed to SearchController, which shows the search results

            .state('search', {
                url: '/search',
                templateUrl: baseDir + 'search/templates/index.html',
                controller: 'SearchController',
                params: {
                    searchPromise: null
                }
            })
    

    landing.controller.js - controller where the user adds search input and submits

        let promise = SearchService.search(form);
        $state.go('search', {
            searchPromise: promise
        });
    

    search.service.js - a service that returns a promise from the user input

        function search(params) {
            return new Promise(function (resolve, reject) {
                $timeout(function() {
                    resolve([]) // mimic a slow query but illustrates a point
                }, 3000)
            })
        }
    

    search.controller.js - where search controller

        let promise = $state.params.searchPromise;
    
        promise.then(r => {
            console.log('search result',r);
        })
    

提交回复
热议问题