0

我正在尝试将当前选项卡 url 发送到资源服务 { in param } 。但是全局 tablUrl 在 var url = "http://[localhost]/getProfile?domain="+tabUrl 处没有任何值

但在以下位置获得记录正确:

console.log(tabUrl);

这是我的代码:

var tabUrl;
angular.module('jsonService', ['ngResource'])
.factory('JsonService', function($resource) {
        chrome.tabs.getSelected(null, function(tab) {
        tabUrl = tab.url;
        console.log(tabUrl);
    });
    var url = "http://[localhost]/getProfile?domain="+tabUrl
  return $resource(url,{}, {
    list : {
      method : 'GET',
     cache : true
    }
 });
});

模板绑定:

  <body ng-controller="extensionCtrl"> 

这是控制器:

app.controller('extensionCtrl', function($scope , JsonService) {
 JsonService.get(function(data){
   $scope.data = data;
  });
 });
4

1 回答 1

2

首先:请不要使用已弃用的chrome.tabs.getSelected。请改用chrome.tabs.query

第二: chrome.tabs.getSelected/chrome.tabs.query异步的。这意味着当他们在后台做一些工作时会继续执行,并在完成后调用指定的回调。
所以,在这样的情况下:

line 1: chrome.tabs.getSelected(null, funkyCallback);
line 2: var url = ...
line 3: return $resource(...);

...一个可能的(并且非常可能的)执行顺序是:

1. chrome.tabs.getSelected (starts retrieving the active tab in the background)
2. line 2 gets executed (at this time 'tabURL' is not set yet)
3. line 3 gets executed (returning something)
4. Once the the active tab is retrieved, 'funkyCallback' is called
   (setting 'tabURL' after it is too late).

使用异步 API(例如大多数chrome.* API)时,您必须更改脚本的整个逻辑以符合 API 调用的异步性质。

例如,你可以达到这样的相同结果:

HTML:

<html ng-app="jsonService">
    ...
    <body ng-controller="extensionCtrl">
        <p>{{jsonData}}</p>
        ...

JS:

var app = angular.module("jsonService", ["ngResource"]);

app.factory("JsonFactory", function($resource) {
    var url = "http://localhost/getProfile?domain=:tabUrl";
    var retObj = $resource(url, {}, {
        list: {
            method: "GET",
            cache: true
        }
    });
    return retObj;
});

app.controller("extensionCtrl", function($q, $rootScope, JsonFactory) {
    chrome.tabs.query({ active: true }, function(tabs) {
        JsonFactory.list({ tabUrl: tabs[0].url }, function(data) {
            // On success...
            $rootScope.jsonData = data;
        }, function(data) {
            // On error...
            $rootScope.jsonData = "Error using JsonFactory.list(...) !";
        });
    });
});

另请参阅这个简短的演示,它执行类似的异步操作

于 2013-10-30T13:52:36.790 回答