You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

报错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 $resource service 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 appid is a valid, active key from OpenWeatherMap—an invalid key will cause API request failures (though that's a separate issue from your current error).
  • $resource expects 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 like get(), query(), etc.

内容的提问来源于stack exchange,提问作者Rahul Pawar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:33:15