如何在Angular中同时使用ngRoute与ngResource模块?
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

