无法在Ionic服务中运行角度spotify方法

Failure to run angular-spotify method in Ionic service

本文关键字:spotify 方法 运行 Ionic 服务      更新时间:2024-01-27

我一整天都在努力处理Ionic服务中Spotify数据的检索,而早些时候有效的东西现在突然不起作用了。

我在一个服务中设置了登录脚本,一切都很好。然而,在updateInfo中使用console.log('updateInfo() called');方法后,程序将跳过该函数的其余部分,从而避免从Spotify收集数据。

这是迄今为止的全部服务:

.factory('SpotifyService', function ($cordovaOauth, Spotify) {
  var currentUser = {},
        userId = '';
    function login() {
        console.log('login() called');
        $cordovaOauth.spotify('583ac6ce144e4fcb9ae9c29bf9cad5ef', ['user-read-private', 'playlist-read-private']).then(function (result) {
            window.localStorage.setItem('spotify-token', result.access_token);
            Spotify.setAuthToken(result.access_token);
        }, function (error) {
          console.log("Error ->" + error);
        });
    }
    function updateInfo() {
        console.log('updateInfo() called');
         Spotify.getCurrentUser().then(function (data) {
            console.log('Gathering data');
            currentUser = data;
            userId = data.id;
            console.log("CURRENT USER: " + userId + " - (" + currentUser + ")");
            console.log('Done updating');
        });
    }
    return {
        getUser: function () {
            console.log('SpotifyService.getUser() called');
            var storedToken = window.localStorage.getItem('spotify-token');
            if (storedToken !== null) {
                console.log('Token accepted');
                currentUser = updateInfo();
                console.log('getUser function returns: ' + userId + " - (" + currentUser + ")");
                //currentUser = Spotify.getCurrentUser();
            } else {
                console.log('getUser else accessed');
                login();
            }
            return currentUser;
        }
    };
})

关于为什么Spotify.getCurrentUser()方法不会运行,有什么想法吗?

您的问题似乎与承诺有关。如果Spotify.getCurrentUser()返回promise,您将不知道错误是什么,因为您还没有定义catch语句。你应该阅读《作为漫画的角度解释》中的承诺,以获得对承诺的简单明了的解释。

修改代码以添加catch语句:

Spotify.getCurrentUser()
.then(function (data) {
    ...
})
.catch(function(error){
    console.log(error);
});

每次使用$cordovaOauth.spotify()或spotify.getCurrentUser()之类的promise时,都必须定义.catch块,这将帮助您进行调试。

将.catch块添加到getCurrentUser()函数调用中以跟踪您的错误,我还建议将auth函数调用中的错误回调模式更改为.catch块以及

.catch(function(error){
  console.log(error);
});