My attempts at retrieving the value of a firebase record are failing. My JSON is as follows:
{
"accounts" : {
"-KRPSyO4B48IpBnHBTYg" : {
"dateCreated" : "",
"email" : "",
"provider" : "",
"userId" : ""
}
},
"products" : {
"-KUKRafaNurpFhGF4jQa" : {
"name" : ""
}
},
"total" : 1
}
I'm trying to return the value of "total". Here's the latest attampt:
var totals = firebase.database().ref('total').once('value', function(products) {});
$scope.totalPosts = totals;
and my HTML:
<div class="card" ng-controller="myController">{{totalPosts}}</div>
All I'm getting is an empty {}. What am I doing wrong?
Thanks in advance!
Firebase queries are asynchronous, try this.
firebase.database().ref('total').once('value', function(products) {
$scope.totalPosts = products.val();
});
Read and write Data
Related
I am facing a problem. I have this json log
{
"log": "Log Info : { \"datetime\" : \"datetime\", \"field1\" : \"value1\", \"field2\" : \"value2\", \"field3\" : \"value3\", \"field4\" : \"value4\", \"field5\" : \"value5\", \"field6\" : \"value6\", \"field7\" : \"value7\", \"field8\" : \"value8\", \"field9\" : \"value9\", \"field10\" : \"value10\", \"field11\" : \"value11\"}\n",
"stream": "stdout",
"kubernetes": {
"pod_name": "pod_name",
"namespace_name": "namespace_name",
"pod_id": "pod_id",
"host": "host",
"container_name": "container_name",
"docker_id": "docker_id",
"container_hash": "container_hash",
"container_image": "container_image"
}
}
I need to get all field inside "log" key. These fields will be increased, so I need to get all fields inside log dynamically. I am using this code to parse json, but the output is this. Maybe someone can help me? Thanks.
const readFile = require("fs").readFile;
readFile("log.json", (err, data) => {
if (err) throw err;
const log = JSON.parse(data);
console.log(log);
});
Output:
{
log: 'Log Info : { "datetime" : "datetime", "field1" : "value1", "
field2" : "value2", "field3" : "value3", "field4" : "value4", "field5" :
"value5", "field6" : "value6", "field7" : "value7", "field8" : "value8"
, "field9" : "value9", "field10" : "value10", "field11" : "value11"}\n',
stream: 'stdout',
kubernetes: {
pod_name: 'pod_name',
namespace_name: 'namespace_name',
pod_id: 'pod_id',
host: 'host',
container_name: 'container_name',
docker_id: 'docker_id',
container_hash: 'container_hash',
container_image: 'container_image'
}
}
You need to JSON.parse also the "inner" json (after you clean it from the prefix)
var obj = {
"log": "Log Info : { \"datetime\" : \"datetime\", \"field1\" : \"value1\", \"field2\" : \"value2\", \"field3\" : \"value3\", \"field4\" : \"value4\", \"field5\" : \"value5\", \"field6\" : \"value6\", \"field7\" : \"value7\", \"field8\" : \"value8\", \"field9\" : \"value9\", \"field10\" : \"value10\", \"field11\" : \"value11\"}\n",
"stream": "stdout",
"kubernetes": {
"pod_name": "pod_name",
"namespace_name": "namespace_name",
"pod_id": "pod_id",
"host": "host",
"container_name": "container_name",
"docker_id": "docker_id",
"container_hash": "container_hash",
"container_image": "container_image"
}
}
var str = (obj.log).substring(obj.log.indexOf(':') + 1);
//console.log(str)
var result = JSON.parse(str);
console.log(result)
I need to do a post request using a JSON file. The JSON is currently looking like this:
{
"compositeRequest" : [{
// Account
"method" : "POST",
"url" : "/services/data/v52.0/sobjects/Account",
"referenceId" : "refAccount",
"body" : {
"Name" : req.body.accName
}
},{
// Contact
"method" : "POST",
"url" : "/services/data/v52.0/sobjects/Contact",
"referenceId" : "refContact",
"body" : {
"LastName" : req.body.conLastName,
"AccountId" : "#{refAccount.id}"
}
},{
// Order
"method" : "POST",
"url" : "/services/data/v52.0/sobjects/Order",
"referenceId" : "refOrder",
"body" : {
"AccountId" : "#{refAccount.id}",
"Pricebook2Id" : PBResult.records[0].Id,
"EffectiveDate" : date,
"Status" : "Draft"
}
},{
// OrderItem
"method" : "POST",
"url" : "/services/data/v52.0/sobjects/OrderItem",
"referenceId" : "refOrderItem",
"body" : {
"Product2Id" : req.params.productId,
"OrderId" : "#{refOrder.id}",
"Quantity" : req.body.itemQuantity,
"PricebookEntryId" : entryResult.records[0].Id,
"UnitPrice" : entryResult.records[0].UnitPrice,
"blng__BillableUnitPrice__c": entryResult.records[0].UnitPrice,
"SBQQ__ChargeType__c": prodResult.records[0].SBQQ__ChargeType__c,
"blng__TaxRule__c": prodResult.records[0].blng__TaxRule__c,
"blng__BillingRule__c": prodResult.records[0].blng__BillingRule__c,
"blng__RevenueRecognitionRule__c": prodResult.records[0].blng__RevenueRecognitionRule__c,
"ServiceDate": date,
"blng__LastChargeToDate__c": date
}
}
]
}
I want to generate more OrderItem objects(indicated in the comment) based on the size of an array, how can I do this? I already have the data that I need to add on the body. Is it possible to create a function to create another OrderItem, and place it after the already existing one (it would even be better if I was going to create the first OrderItem from zero).
Thanks in advance.
If you want to add something to an object, you have to use
Object.assign(myObject, data);
If you want to add something to an array, you have to use:
myArray.push(data);
As I donĀ“t really understand the structure of your data construct, I just try to refer to // OrderItem, which you marked. In this case it would be something like:
let newOrderItem = {
// OrderItem
"method" : "POST",
"url" : "/services/data/v52.0/sobjects/OrderItem",
"referenceId" : "refOrderItem",
"body" : {
"Product2Id" : req.params.productId,
"OrderId" : "#{refOrder.id}",
"Quantity" : req.body.itemQuantity,
"PricebookEntryId" : entryResult.records[0].Id,
"UnitPrice" : entryResult.records[0].UnitPrice,
"blng__BillableUnitPrice__c": entryResult.records[0].UnitPrice,
"SBQQ__ChargeType__c": prodResult.records[0].SBQQ__ChargeType__c,
"blng__TaxRule__c": prodResult.records[0].blng__TaxRule__c,
"blng__BillingRule__c": prodResult.records[0].blng__BillingRule__c,
"blng__RevenueRecognitionRule__c": prodResult.records[0].blng__RevenueRecognitionRule__c,
"ServiceDate": date,
"blng__LastChargeToDate__c": date
}
yourObject.compositeRequest.push(newOrderItem)
I'm developing a chat in angularjs where I have a chat list view and a chat view.
What I'm trying to do is sorting my chat list to show the most recent chat on top using Firebase and JS, I did my research but all of the questions I found they have the date directly as a child but inside my DB my date is inside a 'lastMessage' key. My dates are the following format.
date: 1528417493034
Any help would be highly appreciated
My structure is the following:
"Users": {
"nCsXbTl8CcXvoviuL5Tt7kiV6Bn1" : {
"contacts" : {
"VN9AFnn4uXgDfoir8DWHnw54zrJ3" : {
"email" : "test#test.com",
"lastMessage" : {
"date" : 1528417493034,
"senderId" : "VN9AFnn4uXgDfoir8DWHnw54zrJ3",
"status" : "success",
"text" : "Yes?",
"type" : "text",
"uid" : "1528417493034VN9AFnn4uXgDfoir8DWHnw54zrJ3"
},
"name" : "test"
},
"cHuR26YaSgbO7ahSVLg1XG5HYer2" : {
"email" : "aaa#aaa.com",
"lastMessage" : {
"date" : 1528417068249,
"senderId" : "cHuR26YaSgbO7ahSVLg1XG5HYer2",
"status" : "success",
"text" : "Trigeeeers?",
"type" : "text",
"uid" : "1528417068249cHuR26YaSgbO7ahSVLg1XG5HYer2"
},
"name" : "aaa"
}
}
}
My chat list view is the following:
<div layout="row" class="main-chat-container" layout-wrap>
<div class="list-container" flex="30">
<div class="chat-header">
<p>Lista de Chats</p>
</div>
<div class="chats-list">
<div class="chats-header">
<p>Usuarios</p>
</div>
<div class="chats" ng-repeat="chat in chats">
<div class="email-container" ng-click="setUserData(chat)" ng-class="styleData.email == chat.email ? 'new-background' : ''">
<a>{{chat.email}}</a> <p ng-show="counter > 1">{{testData.number}}</p>
</div>
</div>
</div>
</div>
<div class-"chat-container" flex="70">
<ui-view></ui-view>
</div>
And the controller is the following
app.controller('chatController', function (currentAuth, $scope, $firebaseArray, $firebaseObject) {
$scope.chats = [];
$scope.getContactsList = function(){
var listRef = firebase.database().ref('Users').child(currentAuth.uid).child('contacts');
var test = firebase.database().ref('Users').child(currentAuth.uid).child('contacts');
var listArray = $firebaseArray(listRef);
var testArray = $firebaseArray(test);
$scope.chats = listArray;
console.log("TEST ARRAY IS ");
console.log(testArray);
}
$scope.getContactsList();
});
To so a users contacts on the timestamp of their last message, you'd do something like this:
var userRef = firebase.database().ref('Users').child(currentAuth.uid)
var contactsQuery = userRef.child('contacts').orderByChild("lastMessage/date");
Note that this will give you the contacts in chronological order, so you will have to reverse the result in your client.
Alternatively some folks keep an inverted value in a separate property in their database, e.g.
"VN9AFnn4uXgDfoir8DWHnw54zrJ3" : {
"email" : "test#test.com",
"lastMessage" : {
"date" : 1528417493034,
"invertedDate" : -1528417493034,
"senderId" : "VN9AFnn4uXgDfoir8DWHnw54zrJ3",
Since this invertedDate value is inverted, ordering on that property would give you the contacts in reverse chronological order, so that you don't have to reverse them in the client.
How to check "no_cover" value in thumbnail[0] and replace it to asset/sss.jpg for show listpage
I try to set <img src="{{item.LINKS.thumbnail[0]}}"> in Listpage.html ,this show only thumbnail[0] is http://xxx.jpg, http://xxx.jpg , ,But I have no idea to set "no_cover"
myjson
" DOCSET":{
"DOC":[
{
"LINKS":{
"thumbnail":"http://yyy.jpg",
"thumbnail":"http://....jpg"}
}],
"DOC":[
{
"LINKS":{
"thumbnail":"http://xxx.jpg",
"thumbnail":"http://....jpg"}
}],
"DOC":[
{
"LINKS":{
"thumbnail":"no_cover", <<<<
"thumbnail":"http://....jpg"}
}]
}
EDIT - HOW YOUR JSON SHOULD LOOK
Since I (ivaro18) believe you wrote your JSON by hand and did not copy a response object. Let me show you what valid JSON looks like:
{
"DOCSET" : [
{
"DOC" : {
"LINKS" : [
{
"thumbnail" : "http://.....jpg"
},
{
"thumbnail" : "http://.....jpg"
}
]
}
},
{
"DOC" : {
"LINKS" : [
{
"thumbnail" : "http://.....jpg"
},
{
"thumbnail" : "http://.....jpg"
}
]
}
},
{
"DOC" : {
"LINKS" : [
{
"thumbnail" : "no_cover"
},
{
"thumbnail" : "http://.....jpg"
}
]
}
}
]
}
END OF EDIT
listpage.html
<ion-list>
<ion-item *ngFor="let item of foundRepos">
<ion-thumbnail item-left >
<img src="{{item.LINKS.thumbnail[0]}}"> <!--I have no idea to set it -->
</ion-thumbnail>
</ion-list>
list.page.ts
this.http.get("my_url")
.subscribe(data =>{
this.foundRepos = data.json().DOCSET.DOC;
},error=>{
err => console.error(err),
() => console.log('getRepos completed')
);
So, first of all your JSON you've posted was invalid. edited your question with what it probably is (since you are printing it as you say)
What I understand from your problem is the following, you have <img src="{{item.LINKS.thumbnail[0]}}"> but this throws a 404 when no_cover is returned, that's why, when item.LINKS.thumbnail[0] is equal to 'no_cover' you want to show the image assets/sss.jpg
So, how can we use this to show 'assets/sss.jpg' instead of 'no_cover'? It's called the Elvis operator ( ? : )
Let's assume the following construction for an if-statement:
if(expression) {
result = whenExpressionIsTrue
} else {
result = whenExpressionIsFalse
}
Which we can rewrite with the Elvis operator like this:
result = someExpression ? whenExpressionIsTrue : whenExpressionIsFalse
So, let's check out your problem, how can we do this with an if-statement?
if(item.LINKS.thumbnail[0] == 'no_cover') {
someVariable = 'assets/sss.jpg';
} else {
someVariable == item.LINKS.thumbnail[0];
}
Now shorten it with the Elvis operator:
someVariable = item.LINKS.thumbnail[0] == 'no_cover' ? 'assets/sss.jpg' : item.LINKS.thumbnail[0];
Now this can be used in your HTML like so:
<img
[src]="item.LINKS.thumbnails[0] == 'no_cover' ? 'assets/sss.jpg' : item.LINKS.thumbnails[0]"
/>
im building an gallery app and i need it to be in tree format , im using the jstree extension to build it , and i need the json to be in this format:
$(function () {
$("#demo1").jstree({
"json_data" : {
"data" : [
{
"data" : "A node",
"metadata" : { id : 23 },
"children" : [ "Child 1", "A Child 2" ]
},
{
"attr" : { "id" : "li.node.id1" },
"data" : {
"title" : "Long format demo",
"attr" : { "href" : "#" }
}
}
]
},
"plugins" : [ "themes", "json_data", "ui" ]
}).bind("select_node.jstree", function (e, data) { alert(data.rslt.obj.data("id")); });
});
and im using this database:
categorys:
id
name
id_father
products:
id
name
price
category_id
please help me guys , >_< , im using an MVC structure in my project and its possible to do things like foreach(modelinstance as model) ...
help i realy need it and i have no idea how to build it
This is the function that I use, youll need CNestedSetBehavior in your model though, I recomend this way of setting up hierarquical data, as it is much faster to retrieve:
protected function formatJstree(){
$categories = $this->descendants()->findAll();
$level=0;
$parent = 0;
$data = array();
foreach( $categories as $n => $category )
{
$node = array(
'data'=> "{$category->title}",
'attr'=>array('id'=>"category_id_{$category->category_id}")
);
if($category->level == $level){
$data[$parent]["children"][] = $node;
}
else if($level != 0 && $category->level > $level){
if(!isset($data[$n]["children"])){
$data[$n]["children"] = array();
}
$data[$parent]["children"][] = $node;
}
else
{
$data[] = $node;
$parent = $n;
}
$level=$category->level;
}
return $data;
}