【问题标题】:Using Angular Factory not retrieving bit.ly URL使用 Angular Factory 不检索 bit.ly URL
【发布时间】:2013-11-19 02:57:26
【问题描述】:

我正在尝试在 Angular 中创建一个工厂,它采用编码的 URL 并返回一个缩短的 bit.ly 链接。该代码在控制器中工作,但是当我尝试将相同的代码放入工厂时,我无法让它返回链接。这是我的工厂:

myAppModule.factory('BitlyBuilder', function($http){
return {
    buildBitlyUrl: function(link1){
        $http({ method: 'GET', url: 'https://api-ssl.bitly.com/v3/shorten?access_token=mytokenhere&longUrl='+link1}).
            success(function (data, status, headers, config) {
                return data.data.url;})
            .error(function (data, status, headers, config) {
                console.log('bit.ly failed us');
            });
    }
}});

现在这是我用来调用工厂服务的控制器中的代码:

var encodedLink = encodeURIComponent($scope.feed1.feedlink);
        $scope.shortURL = function (encodedLink) {
            return BitlyBuilder.buildBitlyUrl(encodedLink);
        }
        console.log($scope.shortURL);

我在 console.log 时得到的是:

function (encodedLink) {
            return BitlyBuilder.buildBitlyUrl(encodedLink);
        } 

我确定这很简单,但我不太明白。提前感谢您的帮助...

【问题讨论】:

    标签: angularjs factory


    【解决方案1】:

    看起来 shortURL 函数没有被调用。尝试将其用于您的 console.log 调用:

    console.log( $scope.shortURL(encodedLink) )
    

    【讨论】:

    • 那个错误:对象#的属性'shortURL'不是一个函数“。我认为它会。shortURL不是一个函数。我知道我有一个有效的“encodedLink”,但它没有调用函数。我怀疑我需要某种回调,但不知道如何实现。
    • 嗯,我认为 shortURL 是一个函数。这是一个link to a jsFiddle,它使用shortURL 调用工厂方法。
    【解决方案2】:

    问题是您没有从BitlyBuilder.buildBitlyUrl 返回任何内容。从 successerror 处理程序中返回一些东西没有好处,你在一个封闭的函数中返回。

    即使您返回任何内容,您的 console.log($scope.shortURL); 也不会考虑到 $http 是异步的

    试试这个:

    myAppModule.factory('BitlyBuilder', function($http){
    return {
        buildBitlyUrl: function(link1){
          /* return request itself*/
           return $http({ method: 'GET', url: 'https://api-ssl.bitly.com/v3/shorten?access_token=mytokenhere&longUrl='+link1})
                /* will get data in controller */
               /* .success(function (data, status, headers, config) {
                    return data.data.url;})*/
                .error(function (data, status, headers, config) {
                    console.log('bit.ly failed us');
                });
        }
    }});
    

    在控制器中:

     BitlyBuilder.buildBitlyUrl(encodedLink).success(function(data){
            $scope.shortURL=data.url;// assumes response is {url:'urlstring'}*/
             console.log( $scope.shortURL);
     })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-22
      • 1970-01-01
      • 1970-01-01
      • 2019-09-22
      • 2011-08-20
      • 2023-03-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多