简体   繁体   中英

Why is the 'req' variable considered undefined?

The following code gives me an error every time it is run. The part service.getTracks(req, function(tracks), gives an error on the parameter 'req' saying it is undefined. However, the program still works, it works but still gives an error. I was wondering if anyone could shed some light upon why this happens? I've been staring blindly for 4 hours now, with 0 progress... And help at all is appreciated!

Please ask questions regarding the issue if anything is blurry or something.

Best regards, Victor

app.factory('echonestService', [
'$http',
'$rootScope',
'$cookies',
'$location',
function($http, $rootScope, $cookies, $location) {
    var service = {};
    service.getTracks = function(req, callback) {
        $http(req).then(
            function(res) {
                var tracks = [];
                res.data.forEach(function(e) {
                    tracks.push(e.song_id);
                });
                callback(tracks);
                console.log($rootScope.previews);
                $location.path('/review');
            }
        );
    };

    service.createPlaylist = function(name, tracks) {
        var url = 'http://127.0.0.1:8080/api/create-playlist';
        var data = {
            'user_id': $cookies.get('username'),
            'name': name,
            'tracks': tracks,
            'access_token': $cookies.get('access_token'),
            'refresh_token': $cookies.get('refresh_token')
        };

        $http.post(url, JSON.stringify(data)).then(
            function(res) {
                $rootScope.playlistLink = res.data;
                console.log($rootScope.playlistLink);
                $location.path('/result');
            },
            function(err) {
                console.log("error: ", err);
            }
        );

        service.getTracks(req, function(tracks) {
            data.tracks = tracks;
            $http.post(url, JSON.stringify(data)).then(
                function(res) {
                    $rootScope.playlistLink = res.data;
                    $rootScope.playlistName = name;
                    console.log($rootScope.playlistLink);
                },
                function(err) {
                    console.log("error: ", err);
                }
            );
        });
    };
    return service;
}]);

The only place you're actually using req is here:

$http(req).then(
    function(res) {
    (...etc...)

then() will run after $http even if req is undefined, which is why your code's still working, so you don't need req defined anywhere - but since you're not defining it before using it in $http , you're getting the error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM