【问题标题】:Angular $http.get not passing parametersAngular $http.get 不传递参数
【发布时间】:2016-04-11 02:43:49
【问题描述】:

这似乎是一个简单的问题,我一定忽略了一些小问题。

我有一个访问 Spotify API 并搜索艺术家的函数。我知道通过普通 URL 访问此路由会返回结果。 (例如http://localhost:3001/search?artist=%27Linkin%20Park%27)执行此操作的代码如下:

router.get('/search', function(req, res, next)
{
    var artist = req.param('artist');
    console.log("Artist: " + artist);
    smartSpot.getArtistID(artist, function(data)
    {
        console.log("Data: " + data);
        res.json(data.id);
    });
});

然后,前端有搜索艺术家的代码。这都是通过 Angular 完成的。

angular.module('smart-spot', [])
    .controller('MainCtrl', [
        '$scope', '$http',
        function($scope, $http)
        {
            $scope.createPlaylist = function()
            {
                var artist = $scope.artist;
                console.log(artist);
                window.open("/login", "Playlist Creation", 'WIDTH=400, HEIGHT=500');
                return $http.get('/search?=' + $scope.artist) //this doesn't pass in the artist
                    .success(function(data)
                    {
                        console.log(data);
                    });

            }
        }
    ]);

$http.get() 未正确传递 $scope.artist` 值。

【问题讨论】:

    标签: javascript angularjs node.js express spotify


    【解决方案1】:

    看起来您可能在字符串连接中缺少“艺术家”查询参数。

    $http.get('/search?artist=' + $scope.artist)
    

    或者,您可以将艺术家作为查询参数传递。

    function createPlaylist() {
        return $http.get('/search', { params : { artist : $scope.artist } })
        .then(function(response) {
            return response;
        }, function(error) {
            return $q.reject(error);
        });
    }   
    

    另外,我会避免使用 .success。我相信这已经贬值了,有利于上面的语法。第一个参数是成功函数,第二个是失败函数。

    【讨论】:

    • 哦。呃。对。我知道这很简单。非常感谢!我们无法弄清楚为什么这不起作用。
    • $q 是 Angular 用于管理承诺的服务。如果你想在调用 $scope.createPlaylist 之后做一些事情,你会想从错误函数中返回 $q.reject()。这就是您创建“承诺链”的方式。那么你可以调用 $scope.createPlaylist().then(function(response) {}, function(error) {})。因此,如果 createPlaylist 成功,则运行链中的下一个成功函数。如果 createPlaylists 失败,则运行链中的下一个失败函数。
    • 啊。这是有道理的。
    【解决方案2】:

    你可以通过传递参数

    $http.get('/search', {
        params: {
            artist: $scope.artist
        }
    })
    .success(function(data)
    {
    console.log(data);
    });
    

    【讨论】:

      猜你喜欢
      • 2017-05-08
      • 2016-11-23
      • 1970-01-01
      • 2018-10-13
      • 1970-01-01
      • 2017-01-15
      • 1970-01-01
      • 1970-01-01
      • 2020-08-29
      相关资源
      最近更新 更多