Trying to manipulate the response.data to add isLoggedin = true in the response using .map but its giving me an error of "map" is not a function.
vm.dataResponse = response.data.map(function(data){
data.isLoggedIn = false;
});
Trying to do this so I can have a data to reference whether the user is logged in or not to show (login/sign out). Or I could use $rootScopebut I thought using global is not ideal?
$rootScope.isLoggedIn = false;
then in my vm.login function the $rootScope will then be set to true, this works but when I refresh the page it goes back to false.
response.data will need to be an array in order to use .map
.map will create a new array by iterating through all the values of an existing array and returning the results of a provided callback on each member of the array, eg.
var oldArray = [1,2,3,4];
var newArray = oldArray.map(function(number){
return number * 2;
});
//newArray = [2,4,6,8]
So in your example it wouldn't work even if response.data was an array as you are not returning anything from the callback.
If response.data is an object you can just add the property direct, eg.
response.data.isLoggedIn = false;
If you could do as developer033 suggests and provide the output of a console.log of response.data that would help identify how best to handle it.
Edit:
Because you are just returning a string try:
vm.dataResponse = {username: response.data, isLoggedIn: true}
Related
I have this code that is called in an ajax callback once the data is fetched:
function onFetchCallback(data) {
onFetchCallback.accumData ??= [];
onFetchCallback.timeLine ??= [];
onFetchCallback.tempValues1 ??= [];
onFetchCallback.tempValues2 ??= [];
onFetchCallback.char;
const hasNulls = data.includes(null);
if (!hasNulls) {
//push values into different arrays
} else {
//push the rest of no nulls if there is any...
}
}
I dont find this clean, bacause I am checking if the arrays that accumulate the data are initialized for every callback call. I think it woull be better to have the callback function initialized, so that the arrays are created, and then call the functions that will store the data in the arrays.
So I did:
function onFetchCallback() {
function init() {
onFetchCallback.accumData ??= [];
onFetchCallback.timeLine ??= [];
onFetchCallback.tempValues1 ??= [];
onFetchCallback.tempValues2 ??= [];
onFetchCallback.char;
}
function store(data) {
const hasNulls = data.includes(null);
if (!hasNulls) {
//push values into different arrays
} else {
//push the rest of no nulls if there is any...
}
}
onFetchCallback.init = init;
onFetchCallback.store = store;
}
So then when I need to use my callback I do:
onFetchCallback();
onFetchCallback.init();
myWhateverFunc(onFetchCallback.store);
Being myWhateverFunc the one calling the callback:
function myWhateverFunc(callback) {
$.ajax({
//whatever
})
.done(function (data) {
callback(data); //CALL
});
}
This works and I find it super javasScriptic so I do it all the time. Meaning the onFetchCallback initialization + other methods call to handle the function members. I do not know js in depth so I would like to know of there are any flaws with this pattern, or if there is any other better/cooler/javaScriptStylish way to do this.
The pattern you're using has a lot of resemblence with the function constructor which is more commonly used in JavaScript.
An implementation of your code in the function constructor pattern would like like this:
function FetchCallback() {
this.accumData = [];
this.timeLine = [];
this.tempValues1 = [];
this.tempValues2 = [];
this.char;
}
FetchCallback.prototype.store = function(data) {
const hasNulls = data.includes(null);
if (!hasNulls) {
// push values into different arrays
} else {
// push the rest of no nulls if there is any...
}
};
It enables you to create an object with properties and methods which are predefined. This removes the hassle of repetition when you need multiple instances of this same object.
To use the constructor you'll need to create a new instance with the new keyword. This will return an object with all the properties and methods set.
const fetchCallback = new FetchCallback();
// Note the .bind() method!
myWhateverFunc(fetchCallback.store.bind(fetchCallback));
Edit
You'll need to specifically set the value of this to the created instance that is stored in fetchCallback. You can do this with the bind() method. This methods explicitly tells that this should refer to a specific object.
The reason to do this is that whenever you pass the store method as the callback to the myWhateverFunc, it loses it's context with the FetchCallback function. You can read more about this in this post
The main difference between this and your code is that here the FetchCallback function will be unaltered, where your function is reassigned every time you call onFetchCallback() and onFetchCallback.init(). The constructor pattern will result in more predictable behavior, albeit that the this keyword has a learning curve.
Hello so I am creating a filter search and I 'm trying to collect all the key (tags) that the user press, inside an array, however every time that a new value is push it does override the entire array. So I tried a couple of things, like spread syntax, concat, etc. But with no luck.
So my action looks like this:
const setCurrentFilters = async (context, payload) => {
if (payload) {
context.commit('setCurrentFilter');
}
}
My state
state:{
filters: JSON.parse(sessionStorage.getItem('currentFilters') || '[]'),
}
The mutation
setCurrentFilter(state, payload) {
state.filters.push(payload);
sessionStorage.setItem('currentFilters', JSON.stringify(payload));
}
And my getter
currentFilters(state) {
return state.filters;
},
Thank you in advance for any help : )
This is simply because you set const filters = []; which means that the next condition if (filters.length) will always return false (as you just created this array) and therefore the else statement will execute.
in the else statement you basically push the new payload to the empty array you just initialized - which makes your array always hold only the new value
i believe that you just need to remove the const filters = []; line, and access the filters property that exists in your state
I want to access data inside a list, but I cannot access it using the square brackets []. The getTalonPaie is a function that call the get method from the HttpClient service and it returns me an observable containing multiple values. The problem is when I was to put it in my array, it is not returning me multiples arrays but one weird empty list with data in it.
onSubmit(): void {
this.listeTalonPaie = Array<number>(1);
const test = [1, 2, 3];
this.listeIndividus = this.indS.listeIndividu;
this.listeIndividus.forEach(ind => {
// The function below is returning me an observable (from httpClient.get()) containing
// multiple objects and I want to add them in my array. I used the push method because
// I need a dynamic array since the number of objects returned by the observable is not
// static.
this.rcs.getTalonPaie(ind.id)
.subscribe( data => {
this.listeTalonPaie.push(data.heures);
test2.push(data.heures);
});
});
// The output is [empty] (i)
// 1: 25
// 2: 40
// 3: 36
// length: 4
// __proto__ : Array(0)
console.log('listeTalonPaie ', this.listeTalonPaie);
// The output is [null]
console.log('listeTalonPaie ', JSON.stringify(this.listeTalonPaie));
// The output is undefined
console.log('Un element ', this.listeTalonPaie[0]);
// The output is (3) [1, 2, 3]
console.log('test ', test);
}
I'm not sure if it's the right way to do it. So if you think there is a better method tell me.
So data is an array and you're pushing that array into this.listeTalonPaie (also an array), so you end up with a nested array [[1,2,3]].
Not sure what your intent is but you might want to use concat or spread instead of push.
this.listeTalonPaie = [...this.listeTalonPaie, ...data.heures];
my console.log() was printing me undefined data.
The subscribe method is asynchronous so console.log is running before your data callback gets invoked. Here's a tiny simulation of it:
// mock subscribe implementation
const subscribe = (callback) => {
// wait half a second then invoke callback with some data
setTimeout(() => callback([1,2,3]), 500);
}
let result = [];
subscribe(data => {
result = [...data];
console.log('1:', result);
});
console.log('2:', result); // <-- called before 1
The problem is with the subscription syntax. I think you should make a new function below and provide it to the subscription.
this.rcs.getTalonPaie(ind.id)
.subscribe( data => {
this.listeTalonPaie.push(data.heures);
this.logDataList(data)
});
});
logDataList(data: any) { console.log(data) };
If it possible you can pull data in ngOnInit and then you have an easy way to get data from your variable when you run onSubmit function
I found that there was no actual problem. In fact, my list works, but my console.log() was printing me undefined data. If someone could explain me why I get undefined data in the console instead of the real value I would be happy !
here the user_res is updated but not the state, and I have tried binding this function to this also. but same result :(
let user_res = usr_vote;
user_res.map((vote)=>{
if(vote.id==dat_id){
vote.status = stats
}
})
console.log("update user response:",user_res)
this.setState({user_response:user_res},()=>{
console.log("but this is not uodating : ",this.state.user_response)
});
I don't think even user_res is updating. map doesn't update the original variable. You need to assign the value of .map to something.
user_res = user_res.map((vote)=>{
if(vote.id==dat_id){
return {...vote, status: stats}
} else {return vote}
})
If you check documentation form Array.prototype.map(), you will see that map doesn't modify the original array, it returns a new array with the modified items.
The map() method creates a new array with the results of calling a
provided function on every element in the calling array.
So with that information you can modify your code accordingly,
// create a new array with the modified items
let user_res = usr_vote.map((vote) => {
if(vote.id == dat_id){
vote.status = stats
}
});
// update state with the new array
this.setState({user_response:user_res},()=>{
console.log("but this is not uodating : ",this.state.user_response)
});
PS: stats is not defined anywhere in your snippet. If you are not defining it somewhere in your code that your shared snippet doesn't contain, it is OK but otherwise you need to fix that part too.
I'm trying to get a simple count of objects returned by REST get request from the server to use in another controller in Ember.js
For this reason I need to make an additional request to the server. Basically here's my code and it almost works.. but not quite yet. Maybe someone can figure out why.
It return a PromiseArray, that's why I'm using .then() to access the properties .
App.TestController = Ember.ObjectController.extend({
totalCount: function() {
return this.store.find('question', {test: this.get('id')}).then(function(items) {
var count = items.get('content').get('length');
console.log(count); // This actually logs correct values
return count;
})
}.property('question')
})
It does what it suppose to do and I'm getting correct values printed out in the console.log(), but when I try to use {{totalCount}} in the view template I'm getting [object Object] instead of an integer.
Also, am I properly observing the questions property? if the value changes in its proper controller will the value update?
Thanks
The problem you are seeing is because your are returning a promise as the value of the property and handlebars won't evaluate that promise for you. What you need to do is create a separate function that observes question and then call your store there to update the totalCount-property. It would be something like this.
App.TestController = Ember.ObjectController.extend({
totalCount: 0,
totalCountUpdate: function() {
var that = this;
this.store.find('question', {test: this.get('id')}).then(function(items) {
var count = items.get('content').get('length');
console.log(count);
that.set('totalCount', count);
})
}.observes('question')
})
Alternatively totalCount might lazily set itself, like this:
App.TestController = Ember.ObjectController.extend({
totalCount: 0,
question: // evaluate to something,
totalCount: function() {
var that = this;
that.store.find('question', {test: that.get('id')}).then(function(items) {
var count = items.get('content').get('length');
that.set('totalCount', count);
})
}.observes('question').property()
})