15

我目前正在学习 AngularJS 中的教程。这是我的 controllers.js 文件中的代码。

'use strict';

angular.module ( 'F1FeederApp.controllers' , []                                     )
.controller    ( 'driversController'       , function ( $scope , ergastAPIservice ) {

    $scope.nameFilter = null;
    $scope.driversList = [];

    ergastAPIservice.getDrivers ().success ( function ( response ) {
        $scope.driversList = response.MRData.StandingsTable.StandingsLists [ 0 ].DriverStandings;
    });
});

我收到以下错误:

1) $sceDelegate 策略不允许从 url 加载资源。

2) TypeError: ergastAPIservice.getDrivers(...).success 不是函数

我完全不确定是什么导致了这些错误,我对 Angular 很陌生。我在我的示例和其他示例之间看到的唯一可能的区别是在这段代码中:( services.js )

'use strict';

angular.module ( 'F1FeederApp.services' , []                 )
.factory       ( 'ergastAPIservice'     , function ( $http ) {

    var ergastAPI = {};

    ergastAPI.getDrivers = function () {
        return $http ({
            method : 'JSONP' ,
            url    : 'http://ergast.com/api/f1/2013/driverStandings.json?callback=JSON_CALLBACK'
        });
    };

    return ergastAPI;
});

我注意到的不同之处在于,在我的 getDrivers 函数末尾有一个分号,并且我use strict在文件顶部也有该语句。但是,grunt 拒绝在没有这两行的情况下运行应用程序,所以我认为这不是问题所在。

如果有人能在这里指出我正确的方向,我将不胜感激。

4

2 回答 2

29

问题 #1

根据 AngularJS sceDelegatePolicy,您尝试从应用程序请求的url是不安全的。要解决它,您需要使用$sceDelegateProvider中的方法 将应用中的 url 列入白名单,如下所示:resourceUrlWhitelist

angular.module('myApp', []).config(function($sceDelegateProvider) {  
$sceDelegateProvider.resourceUrlWhitelist([
    // Allow same origin resource loads.
    'self',
    // Allow loading from our assets domain. **.
    'http://ergast.com/**'
  ]);

为了清楚的解释,上面的例子来自这里

问题 #2:

错误问题TypeError: ergastAPIservice.getDrivers(...).success is not a function可能是由于您使用的 AngularJS 版本。.success/.error最新的 AngularJs 版本 1.6 现在不推荐使用旧方法。这是弃用通知如果您使用的是最新的 AngularJs,这可能是原因,否则,我们需要更多信息来调试问题。

于 2017-01-13T20:23:28.190 回答
14

您可以使用以下

$scope.trustSrc = function(src) {
    return $sce.trustAsResourceUrl(src);
}

and your html should have {{trustSrc(myUrl)}} instead of {{myUrl}}
于 2019-02-19T07:02:49.717 回答