我是AngularJS的新手并且在我学习的过程中喜欢它。我试图找出如何使用$ resource和RESTful API从AngularJS与MongoLab进行通信。我有以下两个文件:
index.html:
-----------
<!DOCTYPE html>
<html lang="en">
<head>
<title>MongoLab Connectivity Test</title>
<script src="angular.js"></script>
<script src="angular-resource.js"></script>
<script src="app3.js"></script>
<link rel="stylesheet" href="bootstrap.css" />
<link rel="stylesheet" href="bootstrap-theme.css" />
</head>
<body ng-app="myModule">
<div ng-controller="display">
<p>{{data.message}}</p>
</div>
</body>
</html>
app3.js:
--------
var myModule = angular.module('myModule', ['ngResource']);
myModule.controller('display', function($scope, personService) {
$scope.data = personService.query();
});
myModule.constant({
DB_BASEURL: "https://api.mongolab.com/api/1/databases/db1/collections",
API_KEY: "<MyAPIKey>"
})
myModule.factory('personService', ['$resource', 'DB_BASEURL', 'API_KEY',
function($resource, DB_BASEURL, API_KEY)
{
return $resource
(DB_BASEURL+'/persons/:id'
,{id: "@id" apiKey: API_KEY}
);
}
]);
当我尝试时,我得到以下输出:
{{data.message}}
我不确定我做错了什么。希望得到一些帮助。
答案 0 :(得分:1)
更好的连接方式是:https://github.com/pkozlowski-opensource/angularjs-mongolab
[从文档中复制文本]
首先,您需要包含AngularJS和angular-mongolab.js脚本:https://raw.githubusercontent.com/pkozlowski-opensource/angularjs-mongolab/master/src/angular-mongolab.js
然后,您需要配置2个参数:
MongoLab key (API_KEY)
database name (DB_NAME)
需要在应用程序模块的常量MONGOLAB_CONFIG中指定配置参数:
var app = angular.module('app', ['mongolabResourceHttp']);
app.constant('MONGOLAB_CONFIG',{API_KEY:'your key goes here', DB_NAME:'angularjs'});
然后,创建新资源非常非常简单,归结为使用MongoDB集合名称调用$ mongolabResource:
app.factory('Project', function ($mongolabResourceHttp) {
return $mongolabResourceHttp('projects');
});
只要完成上述操作,您就可以在服务和控制器中注入并使用新创建的资源:
app.controller('AppController', function ($scope, Project) {
Project.all().then(function(projects){
$scope.projects = projects;
});
});
此外,您可以在此处查看博客,以便更简单地实施:http://asad.io/angularjs-with-mongolab/
答案 1 :(得分:0)
使用Angular和Mongolab REST API的$ http模块
对于GET请求,
// RestaurantTableViewController.swift
import UIKit
class RestaurantTableViewController: UITableViewController {
var restaurantNames = ["Cafe Deadend", "Homei", "Teakha", "Cafe Loisl", "Petite Oyster", "For Kee Restaurant", "Po's Atelier", "Bourke Street Bakery", "Haigh's Chocolate", "Palomino Espresso","Upstate","Traif","Graham Avenue Meats","Waffle & Wolf", "Five Leaves", "Cafe Lore", "Confessional", "Barrafina", "Donostia", "Rpyal Oak", "Thai Cafe"]
var restaurantImages = ["cafedeadend.jpg", "homei.jpg", "teakha.jpg", "cafeloisl.jpg",
"petiteoyster.jpg", "forkeerestaurant.jpg", "posatelier.jpg", "bourkestreetbakery.jpg",
"haighschocolate.jpg", "palominoespresso.jpg", "upstate.jpg", "traif.jpg",
"grahamavenuemeats.jpg", "wafflewolf.jpg", "fiveleaves.jpg", "cafelore.jpg",
"confessional.jpg", "barrafina.jpg", "donostia.jpg", "royaloak.jpg", "thaicafe.jpg"]
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return self.restaurantNames.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
// Configure the cell...
cell.textLabel!.text = restaurantNames[indexPath.row]
cell.imageView?.image = UIImage(named: restaurantImages[indexPath.row])
return cell
}
}
对于POST请求,
$http.get('https://api.mongolab.com/api/1/databases/DATABASE_NAME/collections/COLLECTION_NAME?apiKey=YOUR_API_KEY')
.success(function(data) {
console.log(data)
}
有关$http.post('https://api.mongolab.com/api/1/databases/DATABASE_NAME/collections/COLLECTION_NAME?apiKey=YOUR_API_KEY', $scope.data, {
headers: {
'Content-Type': 'application/json; charset=UTF-8'
}
})
.success(function() {
console.log('Data saved successfully')
}
方法支持文档的更多信息 - http://docs.mongolab.com/data-api/#reference