Is it possible to create multiple dataStore in angular-localForage? - javascript

Is it possible to have multiple dataStore in IndexedDB using angular-localForage?
I tried this:
var $tblStage = $localForage.createInstance({
storeName : 'tblStage', // name of the table
});
but it triggered an error which says:
Error: A localForage instance with the name dbName is already defined.
I read this Question before but, is the only way is working with Raw IndexedDB? Or I missed something in my code? Any Idea?

Yes, only configure when you use.
https://github.com/mozilla/localForage#configuration
But no its possible two instance at same db.
If you intend to use the directive, local-forage, you'll have to copy and configure it.
Just like this https://github.com/ocombe/angular-localForage/blob/master/src/angular-localForage.js#L51, for change the provide,
only change defaultConfig at #L20, and name of angular module directive #L465.
And give more information but the reputation is very low and this leaves hook and my English so bad.

Related

Runtime value in forRoot of Angular Module

In my angular app there is this module called Ngx-Stripe
I have defined it as documentation like following:
NgxStripeModule.forRoot('***your-stripe-publishable key***');
But the problem is I don't get this key on app bootstrap, I am not supposed to hardcode it in angular app.module or global like in index.html when I am using stripe withput any angular library.
I am getting this key on the api call after user proceeds to payment page. How can I define this key in this scenario ?
I wish it'd be straightforward, but the only way I was able to achieve it was something like:
index.html (alternatively webpack-injected script), has to be placed before Angular's sources:
<script>
var STRIPE_KEY = 'paste it here';
</script>
app.module.ts:
declare var STRIPE_KEY;
// ...
NgxStripeModule.forRoot(STRIPE_KEY);
The problem here is .forRoot() has to be statically-analyzed by Angular AoT compiler, so it can't accept what you want it to accept... How about setting the key after you got it via StripeService.changeKey(key: string) method?
Simply import StripeService from ngx-stripe and call changeKey on that service once you have your key.
For lazy loading your Stripe config key you can create your own instance of StripeService using StripeFactory that is available from ngx-stripe.
Check the documentation here for a full explanation:
https://richnologies.gitbook.io/ngx-stripe/core-concepts/service-factory

Where to put a particular template helper

I have a pageTitle template variable that is in the header element () of each section of my site, and I would like it to be dynamic, rather than hard-coded, so site maintenance is easier.
Using Meteor (I'm currently reading Discover Meteor), would it be best to put it in a Session variable, and then return the value from a Template helper (i.e. as in the example in the Session chapter of Discover Meteor), or is there an Atmosphere package that would handle this better?
Also, if I do put it in a Template helper, I'm a little fuzzy about where is the appropriate file in which to put the helper. That is, if I have a .js file for (almost) every template (because I'm following along with the book), would I really need to put the same helper code that returns the pageTitle variable from the Session in each template's .js file?
It seems inefficient to have so many redundancies, but if I had a single instance of that Template.templateName.helper() code, I'm not sure where to put it.
Any help is much appreciated. Thanks!
I'd put it inside a global helper. You can use Template.registerHelper for that. I usually put these helpers inside client/helpers/global.js. I'm not sure why you would want to use a session variable for this. But here's a simple example of how this helper could look like:
client/helpers/global.js
Template.registerHelper('setPageTitle', function (newTitle) {
document.title = newTitle
})
Usage:
{{ setPageTitle 'Hi' }}
I'm also fairly new to Meteor, but it looks like you could use the Observe Collection from the docs - http://docs.meteor.com/#/full/observe and have a collection with your pageTitles in it.
So it would be something like
document.title = yourCursor.observe(function({
changed: function(id, field){return field.pageTitle}
})
As for location, anywhere on the client side should work.
Not sure if this is best way to do it, but hope it helps!

breezejs: adding referential constraint to an entity type

This is a follow-up question to my previous issue - this one was getting a bit messy and is more related to the Telerik Data Service.
The metadata I receive from the server are missing the referential constraints in the association node, although I've set the foreign key attribute on my model.
Therefore I was thinking about manually adding these constraints to my entities in the callback of FetchMetadata.
Is that possible and can someone provide a simple example on how to do it ?
[EDIT]
Here's what I have so far:
manager.fetchMetadata().then(function () {
var mandatType = manager.metadataStore.getEntityType("Mandate");
mandatType.autogeneratedKeyType = breeze.AutoGeneratedKeyType.Identity;
var openPositionsProp = new breeze.NavigationProperty({
name: "OpenPositions",
entityTypeName: "OpenPositions:#DirectDebitModel",
isScalar: true,
associationName: "OpenPosition_Mandate_Mandate_OpenPositions",
foreignKeyNames: ["Id"]
});
mandatType.addProperty(openPositionsProp);
});
But it raises the exception:
The 'Mandate:#DirectDebitModel' EntityType has already been added to a MetadataStore and therefore no additional properties may be added to it.
Ok, I have a possible approach that you might be able to use right now.
Fetch the metadata from Teleriks OData feed just like you do now.
Export the metadataStore created as a result of the previous step via the MetadataStore.exportMetadata method. This will return "stringified" json for the same metadata in Breeze's native format. This format is much easier to work with.
Convert this string to json via JSON.parse.
Modify the json to add referential constraint information. See Breeze Native Metadata format docs here
Create a new MetadataStore and import the modified json into it.
Create a new EntityManager with this MetadataStore and use it. This EntityManager should now have complete Breeze metadata for use with the rest of the feed.
Hope this makes sense!
We are planning on releasing a form of hybrid metadata in the next release. Unfortunately, it doesn't cover your case because we are focusing on how to add custom metadata to an existing metadataStore, and not actually edit/modify the existing metadata.
Another alternative is that we (IdeaBlade) do offer consulting for this type of work. We could probably write a tool that does steps 1 thru 6 for you. Please contact breeze#ideablade.com if this is of interest and mention this post.
So you are getting meta data but it doesn't have a relationship between the entities. Hmm I have not gotten metaData AND tried to create additional model properties that are related.
Your best bet is to add a property that is a navigation type on the constructor.
http://www.breezejs.com/sites/all/apidocs/classes/EntityType.html#method_addProperty
If it were me, I would try it this way (or something similar) inside of the constructor -
myEntity.addProperty({
associatedEntity: {
entityTypeName: "AssociatedEntity", isScalar: true,
associationName: "AssociatedEntity_MyEntitys", foreignKeyNames: ["associatedEntityId"]
}
});
Where myEntity is the name of the current entity, AssociatedEntity would be your navigation property, the associatedEntityId is a property of myEntity that refers to the other entity. Of course to have this be a two-way relationship you would need to add a property to AssociatedEntity as well.
associatedEntity.addProperty({
myEntitys: {
entityTypeName: "MyEntity", isScalar: true,
associationName: "AssociatedEntity_MyEntitys", foreignKeyNames: ["myEntityId"]
}
});

How to access generateIdForRecord in Ember-Data?

I'm trying to develop an application using the Fixture Adapter with Ember-Data.
When I try and create a new object (based on a model I've defined), it won't work unless I specify the ID.
If I specify the ID and do this:
var person = SD.Person.createRecord({
id: 234,
name: "test"
});
var person.save();
I get:
Error: assertion failed: An adapter cannot assign a new id to a record
that already has an id. had id: 234 and you
tried to update it with 234. This likely happened because your server
returned data in response to a find or update that had a different id
than the one you sent.
Which makes it sound like somehow I'm updating an existing record (I'm not, there's only 2 fixtures for my Person object with ID's of 1 and 2 respectively).
Is Ember trying to save my object twice somehow?
I thought I may have to try and use generateIdForRecord to set the ID, but I can't reference that function no matter what I try.
newBooking.set('id', this.store.generateIdForRecord(this.store, newBooking));
newBooking.set('id', DS.generateIdForRecord(this.store, newBooking));
newBooking.set('id', this.generateIdForRecord(this.store, newBooking));
newBooking.set('id', generateIdForRecord(this.store, newBooking));
TypeError: this.store.generateIdForRecord is not a function
I'm using the latest releases of Ember and Ember-Data (have tried previous releases too). My model is implemented no differently to the TodoMVC tutorial in the Ember guides and in the tutorial nothing fancy needs to be done to manage ID's with the Fixture adapter so I've really no idea what's going on.
How do I create a new Person object (as per my example, just one 'name' field and persist it using Ember-Data's fixture adapter without the aforementioned errors?
In the end, my first code snippet worked fine.
For some reason, I was expecting to see the new object being persisted in the developer console. My models were being listed in a different view so I didn't realize it was actually working as intended.

Where does data returned by ember-data 'live'?

ya'll I have a bit of a structural/procedural question for ya.
So I have a pretty simple ember app, trying to use ember-data and I'm just not sure if I'm 'doing it right'. So the user hits my index template, I grab their location coordinates and encode a hash of it (that part works). Then on my server I have a db that stores 'tiles' named after there hash'd coords (if i hit my #/tiles/H1A2S3H4E5D route I get back properly formatted JSON).
What I would like to happen next, if to display each of the returned tiles to the user on the bottom of the first page (like in a partial maybe? if handlebars does that).
I have a DS.Model for the tiles, if I hard code the Hash'd cords into a App.find(H1A2S3H4E5D); I can see my server properly responding to the query. However, I cannot seem to be able to figure out how to access the returned JSON object, or how to display it to the user.
I did watch a few tutorial videos but they all seem to be outdated with the old router.
Mainly I would like to know:
1. Where does the information returned by App.find(); live & how to access it?
2. what is the 'correct' way to structure my templates/views to handle this?
3. how should I pass that id (the hash'd coords) to App.find? as a global variable? or is there a better way?
the biggest problem(to me) seems to be that the id I search by doesn't exist until the user hit the page tho first time. (since its dynamically generated) so I can't just grab it when the page loads.
I can post a fiddle if required, but I'm looking for more of a conceptual/instructional answer rather then some one to just write my code for me
I'm still learning a lot with Ember as well, but this is my understanding. When you follow the guides and the tutorials out there, you'll have something like this:
App.TileController = Ember.ObjectController.extend();
App.TileRoute = Ember.Route.extend({
setupController: function(controller) {
controller.set('content', App.Tile.find(MYHASH));
}
});
What it does is set the special content object to the result. So since we're declaring an object controller, and calling find with a parameter, it knows that a single result is expected. So a view & template that follow the naming convention of Tile will be loaded. And in there you can access properties on the Tile object:
<p>{{lat}}</p><p>{{lng}}</p>
I have to admit that this feels a bit mystical at times. The core to it is all in the naming convention. You need to be pretty specific in how you name all your various controllers, routes, etc. Once that's nailed down, it's a matter of binding what data you want to the controller's content.
1) Aside from the generic answer of "in memory", the .find() calls live where ever you return it to. Generally speaking, this is meant to be set on a 'content' property of a controller.
2) I more or less answered this, but generally speaking you take the name of your route, and base it off that. So for a route TileRoute, you have:
TileController = Ember.ObjectController.extend
Tile = DS.Model.extend
TileView = Ember.View.extend
tile.handlebars
I generally store all my handlebars files in a templates/ folder. If you nest them deeper, just specify the path in your view object:
App.TileView = Ember.View.extend({
templateName: "tiles/show"
});
3) This really depends on your app. Generally speaking its better for the id to be either obtained from the URL, or constructed locally in a function. Since you are encoding a hash, i imagine you're doing this in a function, and then calling find. I do something a bit similar for an Array controller.
I don't know at what point you are generating a hash, so let's say it's onload. You should be able to generate the hash just in the setupController function.
App.TileRoute = Ember.Route.extend({
generateHashBasedOnCoords: function() {
// ...
},
setupController: function(controller) {
var MYHASH = this.generateHashBasedOnCoords();
controller.set('content', App.Tile.find(MYHASH));
}
});
I hope that helps.
I believe that you can make use of the data binding in ember and basically have an array controller for tiles and set the content initially to an empty array. Then we you get back your response do a App.find() and set the content of the tiles controller with the data that is returned. This should update the view through the data binding. (Very high level response)
The data itself is stored in a store that is setup with ember data. You access it with the same method you are using the model methods App.Tile.find() ect. It checks to see if the data that is needed is in the store if so it returns the data otherwise it makes a call to the api to get the data.

Categories