Angular updating two different arrays when only one should be updated - javascript

I'm still getting my feet wet with Angular, so keep that in mind as you read about my problem.
I have a series of dynamically generated checkboxes that can be used to grant permissions to other users. Whenever a checkbox is updated, it updates a $scope.permissions array that I have set up in my main controller. The array is populated by an AJAX request that fires when a user to administer is selected from a dropdown.
I want to notify the user if they have unsaved changes before they navigate away or change the user they are wanting to administer. So, I set up a second array called originalPermissions that is set to the same data as the $scopes.permission array, like so:
$http.post(ajaxurl, user_data)
.success(function(data) {
// Get the permissions model from the server and store to the $scope
console.log('Setting');
$scope.permissions = data;
$scope.origPermissions = data;
...}
Then, each of the checkboxes have an ng-click="updatePermission(data.path)" function call. It likes like this:
$scope.updatePermission = function (path) {
//get the position of the target path in the array
var position = $scope.permissions.indexOf(path);
//if it doesn't exist, its position will be -1
if(position == -1){
// Push the path into the Array if it doesn't exist
$scope.permissions.push(path);
} else {
// Remove the permission from the array if it was already there
$scope.permissions.splice(position, 1);
}
console.log('Perms: '+$scope.permissions);
console.log('OldPerms: '+$scope.origPermissions);
}
Even though I am only performing pushes on the $scope.permissions array, the $scope.origPermissions array is getting updated as well (the console.logs are outputting identical things). This is not desirable, because I want to see if the new stuff in permissions is different from what we have in origPermissions; if so, I want to fire a confirmation box saying "You have unsaved changes..." etc.
That said, I know watchCollection() exists in angular, but as far as I understand, watchCollection notifies you whenever the permissions array changes, but there's no way to tell if it is the same as it was when originally set.
So: why would origPermissions get updated along with scope? Is it because I'm setting each array to the same value, so Angular is assuming it's essentially the same thing? Is there a better way to do this that's more in keeping with the "Angular way"?

$scope.permissions = data;
$scope.origPermissions = data;
data "points" to the same array.
You can use slice to return a new array
$scope.permissions = data.slice();
$scope.origPermissions = data;

Related

Angular2/4 - Creating an array of data to share across multiple components via service

Overview:
I have a UI that allows a user to select one or more employees based on various search criteria. When they select them, I need to store the selected employees in an array, within my shared service.
Before any of this data is sent to the server, the array could be modified by adding more employees or removing some that exist in the array.
I need to be able to create and subscribe to an array of data in this shared service.
My Approach:
My initial approach was to use a BehaviorSubject so that I could call next and pass the data along when needed. This became an issue though because I didn't have a way to see all of the stored/selected users, only the last one that was passed through the BehaviorSubject.
Psuedo Code:
shared.service.ts
public selectedUsers = []; //<- How do I store stuff in here?
private selectedUsersSub = new BehaviorSubject<any>(null);
selectedUsers$ = this.selectedUsersSub.asObservable();
setSelectedUsers(data) {
this.selectedUsersSub.next(data);
}
get selectedUsers(){
return this.selectedUsers;
}
component.ts:
this._reqService.selectedUsers$.subscribe(
data => {
if (data) {
console.log('Observable Stream', data)
}
}
)
My goal here is to be able to store my selected employees in this selectedUsers array. My other components need to be able to subscribe so that they are always up-to-date with the current value of selectedUsers.
I also need to be able to access the current array of selected users at any time, not just the last value.
Delete public selectedUsers = [];
delete get selectedUsers(){
return this.selectedUsers;
}
And in any component you want to fetch the selectedUsers just subscribe to the public observable selectedUsers$
in a component
this.subscription = this.yourService.selectedUser$.subscribe((users)=>//do stuff here like push theusersto the users array of the component)
The service needs to be inject to a shared module in order all the components to get the same state (data).
More details: https://angular.io/guide/component-interaction#parent-and-children-communicate-via-a-service
Your approach is wrong here. You have 2 basic options in a shared service pattern. 1 is to use a store pattern where you have a predefined set of data manipulations and use the scan operator, this is more complex, the simpler is to pass the entire list every time you want to update the list.
So your components will not only send the update, they'll first get the entire list and then manipulate and then send it.

Match value of array from database object in Firebase Cloud Functions

This is my first app project using Google Cloud Functions & Firebase. I'm trying to find away to get a single value of the array that I'm returning and compare it to a set variable and if it matches, update another child's value in that same account.
My App users can add records to the database under their login/user_id that is stored in the database. I'm trying to get a list of the "RecordName" that is a child under that login/user_id that every user has stored in their account.
So basically every "RecordName" in the entire database. When I want to run specials for those records, I need to match the name of that record to the name of the record I have on special and if there is a match, update another child value under that user's account ("special" = true.). This way, when they load their app next time, I have it highlighting that record so they know it's on special.
When I use..
const ref = admin.database().ref(`/store`);
...with the following code...
ref.on('value', function(snapshot) {
// puts ALL items of the object into array using function ..
console.log(snapshotToArray(snapshot));
});
... and the function...
function snapshotToArray(snapshot) {
var returnArr = [];
snapshot.forEach(function(childSnapshot) {
var item = childSnapshot.val();
item.key = childSnapshot.key;
returnArr.push(item);
});
return returnArr;
};
... I get the entire array just as it is in the database:
-store
-{ones_users_id}
-recordname: value1
-special: false
-{anothers_users_id}
-recordname: value2
-special: false
ect. ect.
If my record on special is called, "Newbie Record", what would be the best way to take out every individual value for the key: "recordname" from the array, compare each one to var = "Newbie Record" and if they match, update the value of the key: "special" to be true?
I'm new to JSON and NodeJS, I've been searching on here for answers and can't find exactly what I'm looking for. Your feedback would be very helpful.
It sounds like you're looking to query your database for nodes that have "recordname": "Newbie Record" and update them.
An easy way to do this:
const ref = admin.database().ref(`/store`);
const query = ref.orderByChild("recordname").equalTo("Newbie Record");
query.once('value', function(snapshot) {
snapshot.forEach(function(child) {
child.ref.update({ special: true })
});
});
Main differences with your code:
We now use a query to read just the nodes that we want to modify.
We now use once() to read the data only once.
We loop over the children of the snapshot, since a query may result in multiple nodes.
We use the reference of each child and then update its special property.
I recommend reading a bit more about Firebase queries in the documentation.

Ember filtered model entries count

I'm trying to get the number of results of the Ember Data Store filter. E.g
var users = this.store.filter('relevantUser', function(user)
{
return user.get('screenName') == screenName;
});
return user.get('length');
But this always seems to return 0. What am I doing wrong?
I think it should be users.get('length');.
Things to make sure when using filter method of the store.
First argument is the model type. Assuming you have a model named App.RelevantUser then your query is fine, else if the model is App.User then you should be using 'user'.
The var users is actually a DS.PromiseArray instance and not an array actually. Try doing this
this.store.filter('relevantUser',function(user){return user.get('screenName')==screenName}).then(function(relevantUsers){console.log(relevantUsers.get('length'))})
As store.filter queries the server too we need to wait for the promise to resolve before accessing the results. Otherwise they would be always 0.
Incase you are using Chrome. Open up Network Tab in Dev Tools and check the network request going to the server when you run the filter query.

Publishing/Subscribing same collection based on different Session value

I want to publish and subscribe subset of same collection based on different route. Here is what I have
In /server/publish.js
Meteor.publish("questions", function() {
return Questions.find({});
});
Meteor.publish("questionSummaryByUser", function(userId) {
var q = Questions.find({userId : userId});
return q;
});
In /client/main.js
Deps.autorun(function() {
Meteor.subscribe("questions");
});
Deps.autorun(function () {
Meteor.subscribe("questionSummaryByUser", Session.get("selectedUserId"));
});
I am using the router package (https://github.com/tmeasday/meteor-router). They way i want the app to work is when i go to "/questions" i want to list all the questions by all the users and when i visit "/users/:user_id/questions", I want to list questions only by specific user. For this I have setup the "/users/:user_id/questions" route to set the userid in "selectedUserId" session (which i am also using in "questionSummaryByUser" publish method.
However when i see the list of questions in "/users/:user_id/questions" I get all the questions irrespective of the user_id.
I read here that the collections are merged at client side, but still could not figure a solution for the above mentioned scenario.
Note that I just started with Meteor, so do not know in and outs of it.
Thanks in advance.
The good practice is to filter the collection data in the place where you use it, not rely of the subset you get by subscribe. That way you can be sure that the data you get is the same you want to display, even when you add further subscriptions to the same collection. Imagine if later you'd like to display, for example, a sidebar with top 10 questions from all users. Then you'd have to fetch those as well, and if you have a place when you display all subscribed data, you'll get a mess of every function.
So, in the template where you want to display user's questions, do
Template.mine.questions = function() {
return Questions.find({userId: Meteor.userId()});
};
Then you won't even need the separate questionSummaryByUser channel.
To filter data in the subscription, you have several options. Whichever you choose, keep in mind that subscription is not the place in which you choose the data to be displayed. This should always be filtered as above.
Option 1
Keep everything in a single parametrized channel.
Meteor.publish('questions', function(options) {
if(options.filterByUser) {
return Questions.find({userId: options.userId});
} else {
return Questions.find({});
}
});
Option 2
Make all channel return data only when it's needed.
Meteor.publish('allQuestions', function(necessary) {
if(!necessary) return [];
return Questions.find({});
});
Meteor.publish('questionSummaryByUser', function(userId) {
return Questions.find({userId : userId});
});
Option 3
Manually turn off subcriptions in the client. This is probably an overkill in this case, it requires some unnecessary work.
var allQuestionsHandle = Meteor.subscribe('allQuestions');
...
allQuestionsHandle.stop();

backbone.js cache collections and refresh

I have a collection that can potentially contain thousands of models. I have a view that displays a table with 50 rows for each page.
Now I want to be able to cache my data so that when a user loads page 1 of the table and then clicks page 2, the data for page 1 (rows #01-50) will be cached so that when the user clicks page 1 again, backbone won't have to fetch it again.
Also, I want my collection to be able to refresh updated data from the server without performing a RESET, since RESET will delete all the models in a collection, including references of existing model that may exist in my app. Is it possible to fetch data from the server and only update or add new models if necessary by comparing the existing data and the new arriving data?
In my app, I addressed the reset question by adding a new method called fetchNew:
app.Collection = Backbone.Collection.extend({
// fetch list without overwriting existing objects (copied from fetch())
fetchNew: function(options) {
options = options || {};
var collection = this,
success = options.success;
options.success = function(resp, status, xhr) {
_(collection.parse(resp, xhr)).each(function(item) {
// added this conditional block
if (!collection.get(item.id)) {
collection.add(item, {silent:true});
}
});
if (!options.silent) {
collection.trigger('reset', collection, options);
}
if (success) success(collection, resp);
};
return (this.sync || Backbone.sync).call(this, 'read', this, options);
}
});
This is pretty much identical to the standard fetch() method, except for the conditional statement checking for item existence, and using add() by default, rather than reset. Unlike simply passing {add: true} in the options argument, it allows you to retrieve sets of models that may overlap with what you already have loaded - using {add: true} will throw an error if you try to add the same model twice.
This should solve your caching problem, assuming your collection is set up so that you can pass some kind of page parameter in options to tell the server what page of options to send back. You'll probably want to add some sort of data structure within your collection to track which pages you've loaded, to avoid doing unnecessary requests, e.g.:
app.BigCollection = app.Collection.extend({
initialize: function() {
this.loadedPages = {};
},
loadPage: function(pageNumber) {
if (!this.loadedPages[pageNumber]) {
this.fetchNew({
page: pageNumber,
success: function(collection) {
collection.loadedPages[pageNumber] = true;
}
})
}
}
});
Backbone.Collection.fetch has an option {add:true} which will add models into a collection instead of replacing the contents.
myCollection.fetch({add:true})
So, in your first scenario, the items from page2 will get added to the collection.
As far as your 2nd scenario, there's currently no built in way to do that.
According to Jeremy that's something you're supposed to do in your App, and not part of Backbone.
Backbone seems to have a number of issues when being used for collaborative apps where another user might be updating models which you have client side. I get the feeling that Jeremy seems to focus on single-user applications, and the above ticket discussion exemplifies that.
In your case, the simplest way to handle your second scenario is to iterate over your collection and call fetch() on each model. But, that's not very good for performance.
For a better way to do it, I think you're going to have to override collection._add, and go down the line dalyons did on this pull request.
I managed to get update in Backbone 0.9.9 core. Check it out as it's exactly what you need http://backbonejs.org/#Collection-update.

Categories