【问题标题】:Failure to run angular-spotify method in Ionic service无法在 Ionic 服务中运行 angular-spotify 方法
【发布时间】:2016-04-06 17:39:33
【问题描述】:

我整天都在努力处理在 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 曲目超过 30 秒吗?
  • 当时,我正在使用 Spotify 的 Web API,它不允许完整的曲目播放。他们的开发者网站上列出了一些方法,可以帮助您为经过身份验证的用户设置完整的 Spotify 播放器,这需要本地应用程序代码而不是网络应用程序才能运行。

标签: javascript angularjs ionic-framework spotify


【解决方案1】:

您的问题似乎与承诺有关。如果Spotify.getCurrentUser() 返回一个promise,您将不知道错误是什么,因为您还没有定义catch 语句。您应该阅读 Promises in Angular Explained as a Cartoon 以获得对 Promise 的简单清晰的解释。

修改您的代码以添加 catch 语句:

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

【讨论】:

  • 非常有帮助,谢谢。经过几天的正确身份验证后,我从某处获得了错误的访问令牌:/
  • :) 很高兴我能帮上忙。当我开始使用 Promise 时,我遇到了同样的问题。
【解决方案2】:

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

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

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

【讨论】:

    猜你喜欢
    • 2023-03-15
    • 1970-01-01
    • 1970-01-01
    • 2018-11-08
    • 1970-01-01
    • 2018-11-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多