Firebase retrieve Object by Key in JavaScript Api - javascript

Help:
I'm an object of Firebase and can not recover only one item from the list because the key is a objectId and the doc api JS Firebase, it does not have a method to recover for me.
Can you help me?
Controller
var rooms = Rooms.all();
console.log('All Rooms:', rooms);
console.log('Rooms length:', rooms.length);
// New test room
if (!rooms) {
var objRooms = [
{
cc: 'Business 1',
name: 'Chat 1',
city: 'Curitiba',
state: 'PR'
},
{
cc: 'Business 2',
name: 'Chat 2',
city: 'Floripa',
state: 'SC'
}
]
var objRoom = Rooms.save(objRooms);
console.log('ROOMID: ', objRoom.key());
}
Service
.factory('Rooms', function ($firebaseObject) {
// Might use a resource here that returns a JSON array
var ref = new Firebase(firebaseUrl);
var rooms = $firebaseObject(ref.child('rooms'));
return {
all: function () {
return rooms;
},
get: function (roomId) {
// Simple index lookup
console.log('ROOMD:', rooms);
return rooms[ ref.child(roomId) ];
},
save: function (roomData) {
var obj = ref.child('rooms');
var onComplete = function (error) {
if (error) {
console.log('Data could not be saved: ', error);
}
else {
console.log('Data saved successfully!');
}
};
return obj.push(roomData, onComplete);
}
}
})
Output:
Chat Controller initialized!
controllers.js:117 Object {params: Object, current: Object, $current: extend, transition: null}$current: extendcurrent: Objectget: (stateOrName, context)go: go(to, params, options)href: href(stateOrName, params, options)includes: includes(stateOrName, params, options)is: is(stateOrName, params, options)params: ObjectroomId: "-JxlCvzgbdkQfoA1Of78"__proto__: Objectreload: reload()transition: nulltransitionTo: transitionTo(to, toParams, options)__proto__: Object
services.js:78 Selecting the room with id: -JxlCvzgbdkQfoA1Of78
services.js:20 ROOMD: d {$$conf: Object, $id: "rooms", $priority: null}
app.js:43 Logged in as : simplelogin:2
The factory Rooms is a problem:
get: function (roomId) {
// Simple index lookup
console.log('ROOMS:', rooms);
console.log('ROOM specified:', ref.child(roomId).key());
return rooms[ ref.child(roomId) ];
},
[Update]
I created the factory Objects for filter Object data:
.factory('Objects', function () {
return {
filter: function (objectValues, objectKey) {
// to take an action after the data loads, use the $loaded() promise
objectValues.$loaded().then(function () {
// To iterate the key/value pairs of the object, use angular.forEach()
angular.forEach(objectValues, function (value, key) {
if (key === objectKey) {
console.log(objectValues[objectKey]);
return objectValues[objectKey];
}
});
});
}
}
})
and Rooms factory, I edited method get and set:
get: function (roomId) {
return Objects.filter(rooms, roomId);
},
[Update]
I have a database based in the image:
I need list object data.
JavaScript Api
https://www.firebase.com/docs/web/api/

First of all you should use Angularfire which provides some useful methods for using Firebase with AngularJS. You can find the documentation here:
https://www.firebase.com/docs/web/libraries/angular/api.html
Now, your question is how to access an single item using it's key. You can do that simply by just providing the url to that object when retrieving either a $firebaseArray or $firebaseObject (when using Angularfire API):
http://myfirebase.firebase.io/blazing-heat-9118/rooms/ + roomId
And then pass this url to a new Firebase() call:
var ref = new Firebase('http://myfirebase.firebase.io/blazing-heat-9118/rooms/' + roomId);
var room = $firebaseObject(ref);
// To take an action after the data has finished loading, use the $loaded() promise
obj.$loaded().then(function(res) {
console.log(res); // res will be the room object
// To iterate the key/value pairs of the object, use angular.forEach()
angular.forEach(obj, function(value, key) {
console.log(key, value);
});
});
Now you will have fetched the single room from the database.
I'd suggest reading through the Angularfire documentation thoroughly as it contains some great methods for handling your data.

Related

map method not working at some place using javascript / node js

I have Output in JSON format and i want to specific field from it
{
"id":"01",
"name":"fish",
"Data.id":"f01",
"Data.path":"/home/work/fish.jpg"
}
I am using map function to get the value but the problem is i can only fetch the value of id and name not Data.id and Data.path
so i am getting this value from my database and this is my code by how i am getting the value from database
function runRest(req, res) {
let data = req.body;
Owner.findAll({
raw: true,
where: {
id: data.id,
},
include: {
model: kingdom,
required: false,
},
attributes: ["id", "name"],
})
.then((parents) => {
parents.map((value) => {
console.log(value);
});
})
.catch(function (err) {
console.log(err);
});
}
let value={
"id":"01",
"name":"fish",
"Data.id":"f01",
"Data.path":"/home/work/fish.jpg"
};
value.map((data)=>{
console.log(data.id);
});
I can only fetch data which is in white font color which is ID and name any solution how can i get Data.id and Data.path by using map function
I even tried this
let links = value
.map((child) => {
for (let i in child)
if (i === "Data.id") {
return child[i];
}
})
but i don't want to use this for method any chance I can use Map function ?
The object
values = {
"id":"01",
"name":"fish",
"Data.id":"f01",
"Data.path":"/home/work/fish.jpg"
};
Has the keys: "id", "name", "Data.id", "Data.path"
To get the value "f01" you must use the key "Data.id":
foo = values["Data.id"]; // foo === "f01"
In the comments you mention that you want to map an array of these objects to the data id:
idArray = objects.map(value => value["Data.id"]);

Erro when trying to push to array from http request in vue.js

I'm trying to push an object into a response from a axios get request, but i always got an 'push is not a function' error
i'm trying to push inside the .then block of the http request
ps: i'm following the example from the vuejs site
var app = new Vue({
el: '#app',
data: {
message: 'Hello Vue!',
bitCoinValue: null
},
mounted() {
this.getBitcoinValue();
},
filters: {
currencydecimal(value) {
return value.toFixed(2);
}
},
methods: {
getBitcoinValue: function () {
axios.get('https://api.coindesk.com/v1/bpi/currentprice.json')
.then(response => {
this.bitCoinValue = response.data.bpi || [];
this.bitCoinValue.push({code: 'BRL', description: 'Reais', symbol: 'R$', rate_float: 25.50});
});
}
}
})
this is the error message:
Uncaught (in promise) TypeError: this.bitCoinValue.push is not a function
at site.js:21
the problem is that your response from https://api.coindesk.com/v1/bpi/currentprice.json the bpi entry is a Object therefore you can not use push because it is a function for the Array Object.
you have 2 options:
set your value as the similar approach that the api responds
getBitcoinValue: function () {
axios.get('https://api.coindesk.com/v1/bpi/currentprice.json')
.then(response => {
this.bitCoinValue = response.data.bpi || [];
this.bitCoinValue['BRL'] = {code: 'BRL', description: 'Reais', symbol: 'R$', rate_float: 25.50};
});
}
convert the object to array then push
getBitcoinValue: function () {
axios.get('https://api.coindesk.com/v1/bpi/currentprice.json')
.then(response => {
let objectResponse = response.data.bpi || {};
this.bitconValue = Object.values(objectResponse).map(item => item)
this.bitCoinValue['BRL'] = {code: 'BRL', description: 'Reais', symbol: 'R$', rate_float: 25.50};
});
}
Openig your API endpoint in a browser, I found out that the "bpi" key in the response JSON is not an array but rather an object. So, instead of .push()ing a value, you need to set the key directly, i.e. this.bitCoinValue.BRL = {...};.

Infinite functions calls like 'string'.replace().replace()

I'm not really sure how to explain so I will start with the output.
I need to return this:
{
replies:
[
{ type: 'text', content: 'one' }
{ type: 'text', content: 'two' }
{ type: 'text', content: 'three' }
],
conversation: {
memory
}
}
And I wanted to return that through in-line statement.
So I would like to call something like:
reply.addText('one').addText('two').addText('three').addConversation(memory)
Note that addText can be called infinite times while addConversation can be called only one time. Also conversation is optional, in that case, if conversation is absent the conversation object should not appear in the output.
To create a custom structured object use a constructor, say Reply.
To call instance methods on the return value of method calls, return the instance object from the method.
Choices to prevent multiple additions of conversation objects include throwing an error (as below) or perhaps logging a warning and simply not add additional objects after a first call to addConversation.
Write the code to implement the requirements.
For example using vanilla javascript:
function Reply() {
this.replies = [];
}
Reply.prototype.addText = function( content) {
this.replies.push( {type: "text", content: content});
return this;
}
Reply.prototype.addConversation = function( value) {
if( this.conversation) {
//throw new Error("Only one conversation allowed");
}
this.conversation = {conversation: value};
return this;
};
Reply.prototype.conversation = null;
// demo
var reply = new Reply();
reply.addText( "one").addText("two").addConversation("memory?");
console.log( JSON.stringify( reply, undefined," "));
(The console.log uses JSON stringify to avoid listing inherited methods)
A possible implementation is to create a builder as follows:
function create() {
const replies = []; // store all replies in this array
let conversation; // store the memory here
let hasAddConversationBeenCalled = false; // a state to check if addConversation was ever called
this.addText = function(content) {
// add a new reply to the array
replies.push({
type: 'text',
content
});
return this; // return the builder
};
this.addConversation = function(memory) {
if (!hasAddConversationBeenCalled) { // check if this was called before
// if not set the memory
conversation = {
memory
};
hasAddConversationBeenCalled = true; // set that the memory has been set
}
return this; // return the builder
}
this.build = function() {
const reply = {
replies
};
if (conversation) { // only if converstation was set
reply.conversation = conversation; // add it to the final reply object
}
return reply; // finally return the built respnse
}
return this; // return the new builder
}
You can then use it as follows:
const builder = create();
const reply = builder.addText('one').addText('two').addText('three').addConversation({}).build();
Here is a link to a codepen to play around with.
If you specifically want to add assemble this via multiple function calls, then the builder pattern is your best bet, as vader said in their comment.
However, if the goal is to simply create shorthand for concisely building these objects, it can be done using a function that takes the list of text as an array.
const buildObject = (textArray, memory) => {
return Object.assign(
{},
{
replies: textArray.map(x => {
return {
type: 'text',
value: x
}
})
},
memory ? {conversation: memory} : null
)
}
var memory = { };
//with memory
console.log(buildObject(['one', 'two', 'three'], memory ))
//without memory
console.log(buildObject(['one', 'two', 'three']));
Fiddle example: http://jsfiddle.net/ucxkd4g3/

How to push Object element to an array in Vuejs/Javascript

I'm trying to build a small application in VueJs,
Following is my data set:
data(){
return {
pusher: '',
channel:'',
notify: [],
notifications: '',
notificationsNumber: '',
}
},
where I'm having an axios call in created property of components as:
axios.get('api/notifications', {headers: getHeader()}).then(response => {
if(response.status === 200)
{
this.notify = response.data.notifications
this.notificationsNumber = this.notify.length
}
}).catch(errors => {
console.log(errors);
})
I'm having pusherJs implemented, so I'm having following code:
this.pusher = new Pusher('xxxxxxxx', {
cluster: 'ap2',
encrypted: true
});
var that = this
this.channel = this.pusher.subscribe('stellar_task');
this.channel.bind('company_info', function(data) {
console.log(data.notification);
that.notifications = data.notification
});
Once the value is being obtained from pusher I want to push this to my array notify as watch property, something like this:
watch: {
notifications(newValue) {
this.notify.push(newValue)
this.notificationsNumber = this.notificationsNumber + 1
}
}
So the problem is the data format which I'm receiving through pusher is in object form and push function is not getting implemented in this:
Screenshot:
Help me out with this.
I'm making an assumption that response.data.notifications is an Array Like Object.
So all you have to do is:
this.notify = [...response.data.notifications];

How can I pass an data from factory to my controller in angularjs?

I'm trying to move all the business logic from my controller to the factory, but I'm having some trouble passing fields data.
factory.js
app.factory("Quote", function ($resource) {
// TODO: this shouldn't start with /en/
var quoteStatus = [];
var quoteLanguage = [];
var Quote = $resource("/en/quote/api/quote/:id", {}, {
retrieve: {
method: 'GET',
params: {},
isArray: true
},
query: {
method: 'GET',
params: {},
isArray: true,
url: '/en/quote/api/quote/'
},
fields: {
method: 'GET',
url: '/en/quote/api/quote/fields/ '
},
update: {
method: 'PATCH',
},
});
Quote.fields().$promise.then(function (fields) {
var tempObj = [];
for (key in fields.status) {
// must create a temp object to set the key using a variable
tempObj[key] = fields.status[key];
quoteStatus.push({
value: key,
text: tempObj[key]
});
}
for (key in fields.language) {
// must create a temp object to set the key using a variable
tempObj[key] = fields.language[key];
quoteLanguage.push({
value: key,
text: tempObj[key]
});
}
//$scope.addLanguage($scope.language);
Quote.status = quoteStatus;
Quote.language = quoteLanguage;
});
return Quote;
});
controller.js
$scope.quoteStatus = Quote.status;
However this is not working since $scope.quoteStatus is undefined. What am I missing?
Thanks in advance.
You can't expect async operation to behave in synchronous way.
Basically when controller inject Quote in its factory function that time Quote service object gets created & then calls Quote.fields(). hen you ask Quote.status inside a controller will always return undefined. You are not maintaining promise anywhere so that controller will come to know that the data is ready or not.
I think you should introduce $q.when flag there to check the Quote.fields() operation completed or not & then do get the desired variable there.
For implementing above mention thing you need to store the promise of Quote.fields() call somewhere in service. like below
var quoteFieldsPromise = Quote.fields().$promise.then(function (fields) {
/// the code will be same here
};
Then add new method which will hold of quoteFieldsPromise promise object and return the value of quoteStatus & quoteLanguage.
var getQuoteDetails = function(){
$q.when(quoteFieldsPromise).then(function(){
return { quoteStatus: Quote.quoteStatus, quoteLanguage: Quote.quoteLanguage };
})
}
But the way you have returned whole Quote object, which only has $resource object which needs to be changed. I mean to say that the getQuoteDetails method which I've created can not be return with Quote object. So I'd rather rather refactor service to below.
Service
app.factory("Quote", function($resource, $q) {
// TODO: this shouldn't start with /en/
var quoteStatus = [], //kept private if needed
quoteFieldsPromise,
quoteLanguage = [];//kept private if needed
var QuoteApi = $resource("/en/quote/api/quote/:id", {}, {
//inner code is as is
});
//preserve promise of .fields() call
quoteFieldsPromise = Quote.fields().$promise.then(function(fields) {
//inner code is as is
//below lines are only changed.
Quote.status = quoteStatus;
Quote.language = quoteLanguage;
});
var getQuoteDetails = function() {
return $q.when(quoteFieldsPromise).then(function() {
return {
quoteStatus: quoteStatus,
quoteLanguage: quoteLanguage
};
})
};
return {
QuoteApi: QuoteApi,
getQuoteDetails: getQuoteDetails
};
});
Controller
Quote.getQuoteDetails().then(function(quoteDetails){
$scope.quoteStatus = quoteDetails.quoteStatus;
$scope.quoteStatus = quoteDetails.quoteLanguage;
});

Categories

Resources