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

如何在Angular中同时使用ngRoute与ngResource模块?

Fixing ngResource Module Setup in AngularJS

Hey there, let's get your ngResource integration sorted out! You've got two small but critical issues in your code that are causing the problem:

1. Incorrect Dependency Array Syntax

The angular.module function expects the second parameter to be a single array containing all your app's dependencies. You’re passing two separate arrays instead of combining them into one.

2. Typo in Module Name

It’s ngResource (singular), not ngResources (plural) — that’s a common easy-to-miss mistake!

Here’s the corrected code that should work:

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

Important Additional Step

Don’t forget to include the ngResource script file in your HTML before your app’s script. ngResource isn’t part of the core AngularJS library, so you need to add it separately. For example:

<!-- Core AngularJS -->
<script src="angular.min.js"></script>
<!-- ngRoute Module -->
<script src="angular-route.min.js"></script>
<!-- ngResource Module -->
<script src="angular-resource.min.js"></script>
<!-- Your App Script -->
<script src="app.js"></script>

Quick Example of Using $resource for POST

Once the module is set up correctly, you can inject $resource into your controllers or services to handle RESTful POST requests. Here’s a simple implementation:

app.controller("UserController", function($resource) {
  // Define the resource endpoint
  var User = $resource('/api/users/:userId', { userId: '@id' });

  // Create and save a new user via POST
  var newUser = new User({ name: 'Alice', email: 'alice@example.com' });
  newUser.$save(
    function(response) {
      console.log('User created successfully:', response);
    },
    function(error) {
      console.error('Failed to create user:', error);
    }
  );
});

That should get you up and running with RESTful POST functionality using ngResource!

内容的提问来源于stack exchange,提问作者Binay Dhawa

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 06:58:39