I'm new to Firebase and I previously had a JSON file consisting of data I was using in my app, this JSON file was hosted on my own sever - and was working well with my app. Now I'd like to expand the app and try using Firebase to enhance it.
I've gone ahead and created a new account and all and imported my JSON file into firebase, now I'd like to know how I can possibly retrieve this data - I know that simply changing the path to my JSON file might not just be it! Can anyone assist?
Thanks & Regards...
I'm assuming you've already configured the Firebase in your project and installed it, if not just tell me and i'll update my answer.
If you've imported your JSON data into Firebase and you can see it under database on your console now all you'll need to do to read this data is a simple .once() or .on() (i'll explain the differences).
In the page you want to fetch data do this:
import * as firebase from 'firebase';
// LET'S SAY YOU WANT TO FETCH SOMETHING ON HOME PAGE
export class HomePage {
// THIS IS THE PROPERTY WE'LL USE TO SAVE YOUR DATA
private myFirebaseData: any;
constructor(){}
// LET'S FETCH DATA WHEN THE USER FIRST LOADS THE PAGE
ionViewWillLoad(){
firebase.database().ref('Users').once('value', snapshot => {
this.myFirebaseData = snapshot.val();
});
};
}
So explaining a little more of what i've done:
.ref(<string>) is the reference of a node in your firebase database, here i'm fetching all users. You can go as deep as you want, let's say you want the name of a user and you know his ID, you can use .ref(Users/${this.userID}/name) and this'll return his name.
.once() is used to read the data once and value is saying i'll get all the value in the referenced node. You can use .on() and this'll create an observable in that node for the value event. There are other events you can use with .on() and they are child_added, child_moved, child_changed and child_removed.
snapshot.val() is getting all data returned from my callback function.
Here's some useful docs:
Read Events
Querying data
Read, write, delete, update
Hope this helps.
EDIT
Let's say you haven't configured your application to use Firebase, here's the needed steps. Just an observation: i don't use AngularFire2, the methods can be a little differents.
1 - You'll need to install Firebase, so in your project folder use npm install --save firebase on your command console.
2 - In your app.component.js you'll configure your Firebase to point to your project:
import * as firebase from 'firebase';
export class MyApp {
constructor(){
firebase.initializeApp({
apiKey: "key",
authDomain: "domain",
databaseURL: "https://...",
projectId: id",
storageBucket: "bucket",
messagingSenderId: "id"
});
}
}
3 - The properties i used to configure Firebase can be obtained when in your project Firebase console under Settings > general > Add app > Add firebase to your web app (Or something like that).
This is all you'll need and you're ready to use Firebase.
Related
Gday,
Quite new to TS and only got a little bit of experience with backend in general, so apologies if I am completely missing the idea.
So I really like the idea of using Google Secret Manager instead of custom env config for Firebase Functions.
Below is all done within a config.ts within my functions dir.
I need to initialize stripe. Traditional tutorials say to do something like the below example:
import Stripe from 'stripe';
export const stripeSecret = functions.config().stripe.secret;
const stripe = new Stripe(stripeSecret, {apiVersion: '2020-08-27'});
I think it would be ideal to change it to this:
import Stripe from 'stripe'
import {SecretManagerServiceClient} from '#google-cloud/secret-manager';
export async function getSecret(name:string){
const [version] = await secrets.accessSecretVersion({
name: `projects/example/secrets/${name}/versions/latest`,
});
return version.payload?.data?.toString();
}
export const stripeSecret = await getSecret("Stripe-API")
const stripe = new Stripe(stripeSecret, {apiVersion: '2020-08-27'});
But this causes an issue with it being async/await on the top level.
What are my options here and what is best practice?
The Google Secret manager is a useful utility and below are a few best practices when using Secret Manager.
You may try and use following to create and use a secret:
From the root of your local project directory, run the following command:
firebase functions:secrets:set SECRET_NAME
Enter a value for SECRET_NAME.
The CLI echoes a success message and warns that you must deploy functions
for the change to take effect.
Before deploying, make sure your functions code allows the function to access the secret using the runWith parameter:
exports.processPayment = functions
// Make the secret available to this function
.runWith({ secrets: ["SECRET_NAME"] })
.onCall((data, context) => {
const myBillingService = initializeBillingService(
// reference the secret value
process.env.SECRET_NAME);
// Process the payment});
Deploy Cloud Functions:
firebase deploy --only functions
You can also access it like any other environment variable. Conversely, if another function that does not specify the secret in runWith tries to access the secret, it receives an undefined value:
To see the complete best practices list, please visit the next link [1] and to know more about managing secret versions, please take a look at the next link [2].
[1] https://cloud.google.com/secret-manager/docs/best-practices
[2] https://cloud.google.com/secret-manager/docs/managing-secret-versions
I'm working on an App in Angular 6. When the app is deployed, it exchanges data with an online database. When I'm working on the app, however, I would like it to exchange data with a local database. I have a single service setup to do all of the communication, so when I am working on the app I can simply change the base URL, but I was wondering if there was a way I could just redirect that service in development, and then have it go to the database as normal in the production environment.
I am aware I can add a proxy.conf.json file, which I'm already doing to access a separate online API, so I dont know if it is as simple as just adding another element to that json file.
I haven't posted any sample code as this is more of a general question as to methodology in angular versus a specific line of code question, but I'm happy to post whatever people would like to see for clarification.
You can do one thing,
you can configure your url in both environment.ts and environment.prod.ts like
environment = {
...
url: 'something.com/api',
...
}
and use it like
import { environment } from 'environment/environment';
const url = environment.url;
this will give you different url for normal build (Development env.) and prod build (Deploy env.)
Also, don't worry about using just environmet.ts in import statement, as when you create prod build your environment.ts gets content from environment.prod.ts. so you will be using url from environment.prod.ts
In Angular you have access to a function isDevMode() which determines if the app is currently in devmode.
Based on that, you should be able to adjust your base url as needed.
import { isDevMode } from '#angular/core';
private baseUrl: string = '';
const devUrl: string = '...';
const prodUrl: string = '...';
if (isDevMode()) {
this.baseUrl = devUrl
}
else {
this.baseUrl = prodUrl
};
i learn ReactJS, And i have homework task. I need create chat. And i need use mockApi server. I chose Mockoon. Server works fine and i can see my data at React app. But how can i save my data to Api?
this is my axios request:
axios.post(`http://localhost:9000/user/`, { user })
.then(res => {
console.log(res);
})
as i understand {user} should send to api my data.
But if i see at console i can see this:
here what i see at console
my data at config: and not at data: and this only at browser. If i reload page al reseted.
So here question, can i save my data from input to mockapi serve?
This is possible with mockswitch - it supports various connectors example local drive (saves to file system ), github (user defined github account - great if you are doing, mongo etc.
Their docs is available here https://mockswitch.com/docs/#storage
There is no proper documentation for AngularFire2 v5, so I don't know where am i supposed to learn from, but here it's only for Firestore. I don't use firestore, I use Firebase Realtime Database. https://github.com/angular/angularfire2/tree/master/docs
However, I'm pretty new to it, and I'm looking how can I store data in a collection, that would look something like this:
nepal-project-cffb1:
users:
userid:
email: "lajmis#mail.com"
score: 1
My function now looks like this:
this._db.list("users/" + "id").set({
email: this.user,
score: this.score
})
but it doesn't work, I get Expected 2 arguments, but got 1. error. There are a bunch of syntaxes, like .ref .list and i don't know which one to use.
There is an entire section of the AngularFire guide dedicated to RTDB, so I'm confused by the statement that there is no real documentation. Typically you would use valueChanges() to create a list observer as described here for reading, and set() is covered here.
So as that doc illustrates, you need to pass the key of the record to be modified, and also the data to be changed when you call it.
this._db.list("users").set("id", {...});
But if you aren't monitoring the collection, you can also just use db.object directly:
this._db.object("users/id").set({...});
One aspect that may not be immediately intuitive with AngularFire is that it's mainly an adapter pattern intended to take away some of the boilerplate of ferrying data between your Angular model and your Firebase servers.
If you aren't syncing data (downloading a local copy) then there's no reason to use AngularFire here. You can simply call the Firebase SDK directly and avoid the overhead of subscribing to remote endpoints:
firebase.database().ref("users/id").set({...});
I've been wasting all my journey trying to find out a simple tutorial explaining how to make a simple app using ember cli for treating a basic json file...I've read www.ember-cli.com of course, they explain a lot things but..I don't know how to proceed.
Is there a basic example explaining (dummies level) how you make a simple app that parses a json response?
I've used the RESTAdapter, I have build muy model but I don't really know how to make in order to send a kind of response to my template..
this is my persons.js file under app/adapters folder
import DS from 'ember-data';
var ApplicationAdapter = DS.RESTAdapter.extend({
host: 'http://localhost:8000/persons',
namespace: 'person'
});
export default ApplicationAdapter;
this is my persons.js model file under app/model
import DS from 'ember-data';
export default DS.Model.extend({
firstName: DS.attr('string'),
lastName: DS.attr('string'),
occupation: DS.attr('string')
});
This is my handlebars template persons-tmp.hbs file under app/templates/components
<ul>
{{#each model as |item|}}
<li>{{item.firstName}}</li>
{{/each}}
</ul>
My persons.js file undert the folder app/routes
import Ember from 'ember';
export default Ember.Route.extend({
model: function() {
return this.store.findAll('persons');
}
})
and finally the json response of the call to http://localhost:8000/persons:
"person": {
"firstName": "Barack",
"lastName": "Obama",
"occupation": "President"
}
I don't know why but I don't get any data on my template result--..
I also have tried the twilio tutorial (wich is one the best that I've found) ...but even this doesn't work
Sorry for the simplicity!
Your template will not know about the model unless it is defined in your route. Each page of your application should have a corresponding route (if you are using default structure, look in app/routes/yourRoute.js; if you are using pod structure app/your-route/route.js). This is the file where you would hit your model.
If your model is called accounts:
export default Route.extend({
model() {
return this.store.findAll('accounts'),
}
});
Now your template for that route will have access to the model, which comes from your store. Your store uses your adapter to hit the API. If results aren't being returned correctly, make sure the RESTAdapter is serializing the data correctly.
Your model
When you generate your model in ember-cli, you should have entered ember generate model accounts into your terminal/command line. This would create: app/model/accounts.js or (if using pod stucture) app/accounts/model.js.
This model will automatically look to app/adapters/accounts.js if it is there, otherwise it will default to app/adapters/application.js. However, you list a main.js file--which means you are most likely writing this all manually and not using the command line.
If you are using Ember-CLI, you should really try generating everything through the command line/terminal rather than manually adding it yourself. The resolver may give you some unexpected behavior if you are within in an Ember-CLI application.
For the adapter, if your model is called names, it will automatically append it to the namespace/host defined in your application adapter. If you need to get info from superapi.com/names/accounts for instance:
export default RESTAdapter.extend({
host: 'http://superapi.com',
namespace: 'names'
});
If you look in your console, it should tell you the domain you are trying to hit. If you are running on localhost and trying to hit an outside source, your browser may be stopping you for security reasons.
Serving your API locally
If your API is hosted locally on a different port (i.e. in localhost:8000) you can run your ember server through a proxy. When you run your server through the command line you can enter ember server --proxy http://localhost:8000. The benefit of doing this is that you can now update the host of your adapter to api/v1 if your api is normally localhost:8000/api/v1.
Async Data & Promise Chaining
If you aren't getting any errors, Ember is most likely not serving the data fast enough--i.e. it is loading the template before the data is returned from your API. This is when you want to do an RSVP on your model (http://guides.emberjs.com/v1.10.0/routing/asynchronous-routing/)
export default Ember.Route.extend({
model: function() {
return Ember.RSVP.hash({
this.store.findAll('persons')
})
},
setupController: function(controller, hash) {
Ember.setProperties(controller, hash);
}
});
Essentially, it will tell your app not to load certain things until the data has been returned from your API--i.e. it promises to do something upon fetching the data and not before.