angular.js - angular $q问题
高洛峰
高洛峰 2017-05-15 17:06:27
0
2
558
function getMenus() {
    if (!localStorage.getItem('menus')) {
        var defer = $q.defer();
        $http.get('api/menu').success(function (res) {
            // scope.menuList = res;
            localStorage.setItem('menus', res)
            defer.resolve();
            return defer.promise;
        }).error(function (err) {
            defer.reject()
            return defer.promise;
        });

    }
}
getMenus().then(function () {
    scope.menuList = localStorage.getItem('menus')
})

返回结果是angular.min.js:107 TypeError: Cannot read property 'then' of undefined

请问哪里错了。。。。。

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(2)
滿天的星座

The error is reported because the getMenus function has no return value, js returns undefined by default, and then raises then on undefined, so the error is reported
Solution:

Initialized in the first line of getMenus

var defer = $q.defer()

Finally return defer.promise as the return value
In the end it should look like this

function getMenus() {
    var defer = $q.defer()
    if (...) {...}
    return defer.promise
}

Of course there will be problems if you return promises in the success and error callbacks

巴扎黑
function getMenus() {

    var defer = $q.defer();
    
    if (!localStorage.getItem('menus')) {
        
        $http.get('api/menu').success(function (res) {
            // scope.menuList = res;
            localStorage.setItem('menus', res)
            defer.resolve();
        }).error(function (err) {
            defer.reject()
        });

    }
    
    return defer.promise;
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template