报错TypeError: $scope.weatherAPI.get 不是函数的技术求助
Fixing "TypeError: $scope.weatherAPI.get is not a function" in AngularJS forecastController
Hey there, let's break down why you're hitting this error and how to fix it quickly.
The Root Cause
Your mistake is wrapping the entire $resource initialization call inside $sce.trustAsResourceUrl(). Here's what's happening:
$sce.trustAsResourceUrl()returns a trusted URL string, not the resource object that AngularJS's$resourceservice creates.- So when you try to call
$scope.weatherAPI.get(), you're actually trying to run a method on a string—hence the "not a function" error.
The Fix
You only need to apply $sce.trustAsResourceUrl() to the API URL itself, not the whole $resource setup. Here's the corrected code:
weatherApp.controller('forecastController', ['$scope', '$http','$resource', '$routeParams', 'cityService','$sce',function($scope, $http,$resource, $routeParams, cityService,$sce) { $scope.city = cityService.city; // Step 1: Trust the API URL first const trustedWeatherApiUrl = $sce.trustAsResourceUrl("http://api.openweathermap.org/data/2.5/weather"); // Step 2: Create the $resource instance using the trusted URL $scope.weatherAPI = $resource(trustedWeatherApiUrl, { callback: "JSON_CALLBACK" }, { get: { method: "JSONP" }} ); // Now you can safely call the get() method $scope.weatherFinal = $scope.weatherAPI.get({ q: $scope.city, appid:'uniqueid' // Don't forget to use your actual OpenWeatherMap API key here }); }]);
Quick Notes
- Make sure your
appidis a valid, active key from OpenWeatherMap—an invalid key will cause API request failures (though that's a separate issue from your current error). $resourceexpects a URL (trusted or not) as its first parameter, so isolating the URL trust step keeps the resource object intact with all its built-in methods likeget(),query(), etc.
内容的提问来源于stack exchange,提问作者Rahul Pawar
相关产品推荐
相关产品推荐

