Hi i am trying to figure out how to loop through a request table with a user key that has only reqdetails. I have tried following the docs, but it's not working.
I just need to filter out all the user key that has only reqdetails only. For example user key of OAJ2WNWQPUfwJCpAJ11FWIA8kPn2 has a reqdetails.
Btw i am following this link:
https://firebase.google.com/docs/reference/js/firebase.database.DataSnapshot
Here is my firebase console:
Here is my declaration and constructor
request: FirebaseListObservable<any>;
userkey: FirebaseListObservable<any>;
reqdetails: FirebaseListObservable<any>;
userreq: FirebaseListObservable<any>;
constructor(public navCtrl: NavController, public navParams: NavParams, angFire: AngularFireDatabase) {
this.request = angFire.list('/request');
this.userreq = angFire.list(`${this.userkey}`);
this.reqdetails = angFire.list('reqdetails');
}
Here is my OpenMapPage method
openMapPage()
{
let process = this.request.subscribe(records => {
// your logic
records.forEach(record => {
var ref = firebase.database().ref("request");
ref.once("value")
.then(function(snapshot) {
var a = snapshot.exists(); // true
var c = snapshot.hasChild("reqdetails"); // true
var d = snapshot.child('reqdetails').exists();
if (snapshot.hasChild('reqdetails'))
{
console.log(record.$key);
}
});
});
});
this.navCtrl.push(MapPage);
}
You need to specify the key of your target request or loop on all requests.
If you know the key :
ref.child(REQUEST_KEY).once("value", function(snapshot) {
var requestKey = snapshot.key;
var requestValue = snapshot.val();
var reqdetails = requestValue.reqdetails;
console.log(reqdetails);
}
If you want all requests :
ref.once("value", function(snapshot) {
var requestsKey = snapshot.key;
var requestsValue = snapshot.val();
snapshot.forEach(function(childSnapshot) {
var requestKey = childSnapshot.key;
var requestValue = childSnapshot.val();
var reqdetails = requestValue.reqdetails;
console.log(reqdetails);
});
}
Related
public class Home
{
string CustEmail { get;set;}
string CustName { get; set;}
int id { get; set;}
}
Model
[HttpPost]
public void CreateCustomer(Home cust)
{
if (ModelState.IsValid)
{
}
}
Controller
angular.module('myFormApp', []).controller('CustomerController', function ($scope, $http, $location, $window) {
debugger;
$scope.cust = {};
$scope.message = '';
$scope.result = "color-default";
$scope.isViewLoading = false;
//get called when user submits the form
$scope.submitForm = function () {
$scope.isViewLoading = true;
console.log('Form is submitted with:', $scope.cust);
//$http service that send or receive data from the remote server
var cust = {
CustEmail: $scope.cust.CustEmail,
CustName: $scope.cust.CustName,
id: 1,
};
$http(
{
method: 'POST',
url: '/Home/CreateCustomer',
data: cust,
}).then(function (data, status, headers, config) {
$scope.errors = [];
if (data.success === true) {
$scope.cust = {};
$scope.message = 'Form data Submitted!';
$scope.result = "color-green";
$location.path(data.redirectUrl);
$window.location.reload();
}
else {
$scope.errors = data.errors;
}
})
$scope.isViewLoading = false;
}
}).config(function ($locationProvider) {
//default = 'false'
$locationProvider.html5Mode(true);
});
I get the data in the proper format in front-end and the post-back call is also working but I cannot get value in MVC controller. I don't know what am I doing wrong. I have tried using the individual item in controller then it's working fine but i want it through model only.
The .then method of a promise only exposes one value, not four values.
$http(
{
method: 'POST',
url: '/Home/CreateCustomer',
data: cust,
̶}̶)̶.̶t̶h̶e̶n̶(̶f̶u̶n̶c̶t̶i̶o̶n̶ ̶(̶d̶a̶t̶a̶,̶ ̶s̶t̶a̶t̶u̶s̶,̶ ̶h̶e̶a̶d̶e̶r̶s̶,̶ ̶c̶o̶n̶f̶i̶g̶)̶ ̶{̶
}).then(function (response) {
var data = response.data;
var status = response.status;
var headers = response.headers;
var config = response.config;
$scope.errors = [];
if (data.success === true) {
$scope.cust = {};
$scope.message = 'Form data Submitted!';
$scope.result = "color-green";
$location.path(data.redirectUrl);
$window.location.reload();
}
else {
$scope.errors = data.errors;
}
})
For more information, see
AngularJS $http Service API Reference - returns
UPDATE
You can add a .catch block to console log any errors:
$http(
{
method: 'POST',
url: '/Home/CreateCustomer',
data: cust,
̶}̶)̶.̶t̶h̶e̶n̶(̶f̶u̶n̶c̶t̶i̶o̶n̶ ̶(̶d̶a̶t̶a̶,̶ ̶s̶t̶a̶t̶u̶s̶,̶ ̶h̶e̶a̶d̶e̶r̶s̶,̶ ̶c̶o̶n̶f̶i̶g̶)̶ ̶{̶
}).then(function (response) {
var data = response.data;
var status = response.status;
var headers = response.headers;
var config = response.config;
$scope.errors = [];
if (data.success === true) {
$scope.cust = {};
$scope.message = 'Form data Submitted!';
$scope.result = "color-green";
$location.path(data.redirectUrl);
$window.location.reload();
}
else {
$scope.errors = data.errors;
}
console.log("OK:", response.data);
}).catch(function(response) {
console.log("ERROR:", response);
});
am using node js for the lambda function. I need to check whether the emailID exists or not in the dynamo db...If the emailID exists it should prompt to the user that emailid already exists if not it should store the values in the dynamo db ....
EmailID is the sort key
Customername is the primary key
How can i do that ..
Below is my code:
var doc = require('aws-sdk');
var dynamodb = new doc.DynamoDB()
var tableName = "Testing";
exports.handler = (event, context, callback) => {
var EmailID = event.EmailID; // or any other var which is having emaiID
console.log(event)
var params = {
TableName: "Testing",
Key: { EmailID : "abc#gmail.com",
CustomerName : "ABC"},
AttributeUpdates: {
verified: {
Action: "PUT",
Value: true
}
}
};
// Update the user.
dynamodb.update(params, function(err, data)
{
if (err)
{
console.log(JSON.stringify(err));
context.fail(JSON.stringify(err));
return;
}
context.succeed("User successfully updated.");
});
putItem
var AWS = require('aws-sdk');
var docClient = new AWS.DynamoDB.DocumentClient();
exports.handler = (event, context, callback) => {
// TODO implement
var tableName = "Testing";
console.log(event.EmailID)
var parms = {
TableName : tableName,
Item : {
"EmailID" : event.EmailID,
"CustomerName" : event.CustomerName,
"PersonName" : event.PersonName,
"EmailSent" : event.EmailSent,
"Password" : event.Password
}
};
docClient.put(parms, function(err, data)
{
if (err){
callback(err)
}
else
{
callback(null,"Successfully updated data!!!")
}
})
};
To achieve this I would use the Put operation and use the "exists" parameter. Setting it to false will make sure the put operation will fail if an item already exists. When there is no match then put will insert the record.
For more details on how to use this operation in javascript please check out the documentation:
https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB.html#putItem-property
So in your put example you could add the following to your params:
var AWS = require('aws-sdk');
var docClient = new AWS.DynamoDB.DocumentClient();
exports.handler = (event, context, callback) => {
// TODO implement
var tableName = "Testing";
console.log(event.EmailID)
var parms = {
TableName: tableName,
Item: {
"EmailID": event.EmailID,
"CustomerName": event.CustomerName,
"PersonName": event.PersonName,
"EmailSent": event.EmailSent,
"Password": event.Password
},
ConditionExpression: "attribute_not_exists(EmailID)"
};
docClient.put(parms, function (err, data) {
if (err) {
callback(err)
}
else {
callback(null, "Successfully updated data!!!")
}
})
};
My objective is to pass data from page to page. However this error is bugging me. i have declare the navCtrl at the constructor
My constructor for request.ts
constructor(public navCtrl: NavController, public navParams: NavParams, angFire: AngularFireDatabase) {
this.request = angFire.list('/request');
this.userreq = angFire.list(`${this.userkey}`);
this.reqdetails = angFire.list('reqdetails');
}
my html page for request.html
<button class="nearby" ion-button large (click)="openMapPage()">Nearby</button>
my OpenPage method for request.ts
openMapPage()
{
var ref = firebase.database().ref("request");
ref.once("value")
.then(function(snapshot) {
var a = snapshot.exists(); // true
var c = snapshot.hasChild("reqdetails"); // true
var d = snapshot.child('reqdetails').exists();
var requestsKey = snapshot.key;
var requestsValue = snapshot.val();
snapshot.forEach(function(childSnapshot) {
var requestKey = childSnapshot.key;
var requestValue = childSnapshot.val();
var reqdetails = requestValue.reqdetails;
if(reqdetails)
{
this.data = requestKey;
console.log(this.data);
//this.arr.push(requestKey);
//console.log(this.arr);
}
});
this.navCtrl.push(MapPage, {'param1':this.data});
});
}
So after the user clicks on the OpenMapPage() from the request.html it will go to the openMapPage method found in reqeuest.ts and it will render the data to the map.html page
my map.html page:
<ion-list>
<ion-card *ngFor="let user of request | async" class="job">
<ion-avatar class="avatar" item-start>
<img src="../assets/icon/user_male-512.png">
</ion-avatar>
<h2 class="name">{{user.regdetails.username}}</h2>
<p text-wrap class="address"><ion-icon name="compass"></ion-icon> {{user.regdetails.address}}</p>
<p id="key">{{user.$key}}</p>
</button>
</ion-card>
</ion-list>
Now the error i am getting is this:
You should use Arrow functions. By using arrow functions, the this property is not overwritten and still references the component instance (otherwise, the this keyword points to the inner function, and your component's methods and variables are not defined in it):
openMapPage() {
var ref = firebase.database().ref("request");
ref.once("value").then((snapshot) => { // <------ Here!
var a = snapshot.exists(); // true
var c = snapshot.hasChild("reqdetails"); // true
var d = snapshot.child('reqdetails').exists();
var requestsKey = snapshot.key;
var requestsValue = snapshot.val();
snapshot.forEach((childSnapshot) => { // <------ And here!
var requestKey = childSnapshot.key;
var requestValue = childSnapshot.val();
var reqdetails = requestValue.reqdetails;
if (reqdetails) {
this.data = requestKey;
console.log(this.data);
//this.arr.push(requestKey);
//console.log(this.arr);
}
});
this.navCtrl.push(MapPage, { 'param1': this.data });
});
}
You are using a regular function as a callback in snapshot.forEach.
Use arrow function so that this will refer to the class object or use a temporary variable to save this before the call.
snapshot.forEach((childSnapshot) => {
var requestKey = childSnapshot.key;
var requestValue = childSnapshot.val();
var reqdetails = requestValue.reqdetails;
if(reqdetails)
{
this.data = requestKey;
console.log(this.data);
//this.arr.push(requestKey);
//console.log(this.arr);
}
});
Note: Also use arrow function in the outer callback
How to update a document in Document db using queries ( basically want to update a document using a stored procedure)?
The following sample might be what you need: https://github.com/aliuy/documentdb-serverside-js/blob/master/stored-procedures/update.js.
Here's a simplified version:
function updateSproc(id, update) {
var collection = getContext().getCollection();
var collectionLink = collection.getSelfLink();
var response = getContext().getResponse();
tryQueryAndUpdate();
function tryQueryAndUpdate(continuation) {
var query = {query: "select * from root r where r.id = #id", parameters: [{name: "#id", value: id}]};
var requestOptions = {continuation: continuation};
var isAccepted = collection.queryDocuments(collectionLink, query, requestOptions, function (err, documents, responseOptions) {
if (err) throw err;
if (documents.length > 0) {
tryUpdate(documents[0]);
} else {
throw new Error("Document not found.");
}
});
}
function tryUpdate(document) {
var requestOptions = {etag: document._etag};
var fields, i;
fields = Object.keys(update);
for (i = 0; i < fields.length; i++) {
document[fields[i]] = update[fields[i]];
}
var isAccepted = collection.replaceDocument(document._self, document, requestOptions, function (err, updatedDocument, responseOptions) {
if (err) throw err;
response.setBody(updatedDocument);
});
}
I have a service with the following function,
public object Get(AllUsers request)
{
var users = XYZ.GetAllUsers();
var userList = users.Cast<XYZ>();
return new AllUsers
{
UsersAcc = userList.Select(ConvertToEntity).ToList()
};
}
I am trying to get the results from angular controller.
function UserAccountController($scope, $location, $filter, UserAccount) {
#scope.items = function(){
var abc = UserAccount.query();
return abc.UsersAcc
}
}
Here is my Service
angular.module('userAccService', ['ngResource']).factory('UserAcc', function($resource) {
return $resource('/api/useracc/:id', {}, {
query: {
method: 'GET',
}
});
I am new to angular service, and can't seem to make it to work.
You need to create an array object and return it. After the query is done you can populate that same instance with the list UsersAcc. Keep in mind that $scope.items will be [] untill the query returns with data.
$scope.items = getUsersAcc();
function getUsersAcc() {
var dataArray = new Array();
UserAccount.query(function (data) {
var list = data.UsersAcc;
for (var i = 0, c = list.length; i < c; i++) {
dataArray.push(list[i]);
}
};
return dataArray;
};