I have problem with google chart. I get error in console:
overview-statistic-chart-ctrl.js:102 Uncaught (in promise) TypeError: Cannot read property 'map' of undefined at callback (overview-statistic-chart-ctrl.js:102) at loader.js:242
When I refresh or click on some other link and go back to the same link it's work great. But I get this error only when I first time load page.
This is my code:
google.charts.load('current', {
callback: function () {
var teamNames = $scope.teams.map(team => team.team_name);
var days = $scope.teams.map(team => team.date_activity);
var avgMaxHRLastDays = $scope.teams.map(team => team.avgMaxHRLastDays);
var days = $scope.teams.map(team => team.date_activity);
var withDates = avgMaxHRLastDays.map(data => data);
var newArray = matrixTranspose(withDates);
var dataChart = newArray.map(data => [''].concat(data));
console.log("dataChart ", dataChart);
var filled = dataChart.map(data => fillWithZeros(data, $scope.teams.length));
var dataToVisualize = [
["Teams"].concat(teamNames),
].concat(filled);
var data = new google.visualization.arrayToDataTable(dataToVisualize);
var chart = new google.visualization.LineChart(document.getElementById('heartOverviewChart'));
chart.draw(data, optionsDesktop);
},
packages: ['corechart']
});
Thank you for help!
Your $scope.teams seem to not be set properly (this will default the 'teams' property to undefined) So when you are trying to map over the expected 'teams' array you see the error.
Make sure your $scope and the properties in $scope (here $scope.teams) are set properly before you try accessing them in the callback function.
Maybe a couple of log statements or debugging it with a couple of break points might help.
When I refresh or click on some other link and go back to the same link it's work great.
this might happen because by the time you perform those "other" operations the $scope.teams might have the expected value or maybe those "other" operations are setting the $scope.teams value.
Related
I am trying to fecth some data from a google spreadsheet in an AppScript standalone file.
I tried with this piece of code, but it is definitely incomplete. It raises this error:
TypeError: Cannot read property 'getDataRange' of undefined
My function:
var sheet=SpreadsheetApp.openById('1n2a5iecKo7seMXcef81V_pxWSRjE4agQ9DSoROtf0').getSheets()[0]
function getColumnId(sheet, namecol) {
var data = sheet.getDataRange().getValues();
var col = data[0].findIndex((name) => name === namecol) + 1;
return col;
}
After extracting the column data, I want to store that data in a normal list:
var IDCol=getcolumnId(sheet, 'ID')
var AFCol=getcolumnId(sheet, 'AF')
Is that possible in this way? I'd do debugging but I do not know how to proceed first with my function.
I believe your goal is as follows.
You want to retrieve the values from a column using the function getColumnId(sheet, namecol).
Modification points:
Your function name is getColumnId. But you are trying to call the function with getcolumnId. I think that an error occurs.
var sheet=DriveApp.getFileById('1n2a5ieOMcKo7seMXcef81V_pxWSRjE4agQ9DSoROtf0').getBlob() is Blob. In your script, an error occurs at var data = sheet.getDataRange().getValues().
In order to retrieve the values from the column, I think that it is required to retrieve the values using the value of col. For this
Modified script:
function getColumnId(sheet, namecol) {
var data = sheet.getDataRange().getValues();
var col = data[0].findIndex((name) => name === namecol);
var transpose = data[0].map((_, c) => data.map(r => r[c])); // Here, "data" is transposed.
return transpose[col];
}
// Please run this function.
function sample() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1"); // Please set the sheet name.
var IDCol = getColumnId(sheet, 'ID')
var AFCol = getColumnId(sheet, 'AF')
console.log(IDCol)
console.log(AFCol)
}
When this modified script is run, the values of columns with the header values of ID and AF.
Reference:
map()
Added:
From your following replying and your updated question,
Hi Tanaike, I will definitely use your approach mapping the values as you said. But first of all I need to read the data from gsheet properly. Please see my Edit and the error is raised. My code is not place in the google spreadsheet itself but in a StandAlone file in AppsScript
I tried with this piece of code, but it is definitely incomplete. It raises this error:
TypeError: Cannot read property 'getDataRange' of undefined
If you are trying to directly execute the function getColumnId(sheet, namecol) by the script editor, such an error occurs, because sheet is undefined. I thought that this might be the reason for your current issue. From this situation, I thought that you might want to use sheet, IDCol and AFCol as the global variable. If my understanding is correct, how about the following sample script?
Sample script:
var sheet = SpreadsheetApp.openById('###').getSheets()[0];
function getColumnId(sheet, namecol) {
var data = sheet.getDataRange().getValues();
var col = data[0].findIndex((name) => name === namecol);
var transpose = data[0].map((_, c) => data.map(r => r[c]));
return transpose[col];
}
var IDCol = getColumnId(sheet, 'ID')
var AFCol = getColumnId(sheet, 'AF')
// Please run this function.
function myFunction() {
console.log(IDCol)
console.log(AFCol)
}
In this function, when myFunction is run, you can see the values at the log.
I use Google Tag Manager to implement Google Analytics. Thus, the tracker names initiated on my site are not always the same eg. gtm2, gtm3.
The overall objective is to be able to send data to my custom metric as follows:
ga( 'gtm2.set', 'metric2', 'custom metric data');
I can't figure out why this code would not work:
var yone = (ga.getAll()[1].get("name"));
var ytwo = ".set";
var ythree = yone.concat(ytwo);
ga( ythree, 'metric2', 'custom metric data');
The error in Javascript console is that "VM3324:1 Uncaught TypeError: ga.getAll is not a function". I am not sure why this is showing since when I do console.log(ga.getAll()[1].get("name"));, the correct tracker name shows up in console log ie. gtm2.
EDIT
I tried out introducing the callback function as mentioned by #balexandre so my code became this:
var yone = ga(function() {
ga.getAll()[1].get("name")});
var ytwo = ".set";
var ythree = yone.concat(ytwo);
ga( ythree, 'metric2', 'custom metric data');
In this instance, console now shows a different error message "Uncaught TypeError: Cannot read property 'concat' of undefined".
Thanks.
it's a callback, so, you can't just call your code and hope all will work, it will not!
you tried this
var yone = ga(function() {
ga.getAll()[1].get("name")
});
var ytwo = ".set";
var ythree = yone.concat(ytwo);
ga( ythree, 'metric2', 'custom metric data');
but when you're in line var ytwo you don't have anything in yone yet, the call not yet fired... hence it's a callback (will only execute the code when the script is loaded), you don't know if it takes 1ms or 10 sec...
so, you should try:
ga(function() {
// debugger;
var yone = ga.getAll()[1].get("name");
var ytwo = ".set";
var ythree = yone.concat(ytwo);
ga( ythree, 'metric2', 'custom metric data');
});
and if you want, remove the comment and use the browser debugger to check all existing variables and execute the code, inside the callback...
Have you tried with index 0 instead 1? Like this:
ga.getAll()[0].get("name");
The result if you not use GTM could be t0, with GTM could be gtmxx.
Suppose I have some data in firestore. When I call the "Calculation" Function then for each matched element "alld" array is pushed with new objects.
After push(), I get, console.log(alld); It is ok.
But when I call getBl() function, and console.log(alld.n); then it shows all the data, and also showing Error: "TypeError: Cannot read property 'n' of undefined at b.$scope.getBl". I could not understand the reason. I know get() is an asynchronous function. I also applied $scope.$applyAsync();. Is this the reason, or there exist some other reason, I don't know.
What could be the solution?
var app = angular.module('myApp', ['firebase', 'ngRoute', 'angular.filter']);
app.controller('mCntlr', function ($scope, $firebaseArray) {
var alld=$scope.alld=[{'n':j,'d':h,'c':l}];
$scope.getBl=function (b){
let i=0;
for(i=0;i<alld.length;i++)
console.log("check = "+$scope.alld[i].n); //Consol.log is printing data but it also showing "TypeError: Cannot read property 'n' of undefined"
};
$scope.Calculation = function (e) { firebase.firestore().collection("DataCollection").get()
.then(function (snapshot) {
snapshot.docs.forEach(element =>{
fld =element.data();
fld.dC.forEach(function(item){ alld.push({'n':item.A,'d':dr,'c':c});
$scope.$applyAsync();});
});
console.log(alld); //it is ok
$scope.getBl();
}).catch(function (err) {
console.log(err);
});
};
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
Try using this
console.log("check = "+alld[i].n);
As the values of those objects (n,d,c) were undefined you were getting this error.
Or instead of using let i=0; try using var i=0;
and instead of using var alld=$scope.alld=[{'n':j,'d':h,'c':l}]; try using $scope.alld=[{'n':j,'d':h,'c':l}];
then you must have to write console.log($scope.alld);
I'm following the Progressive Web App lab from Google and it says that it's using localStorage for simplicity but that we should change it to idb.
Basically, we want to store a list of cities to display their weather information.
I tried using plain idb following the info here but I think I'm too new to this and I couldn't get any of this. Am I supposed to do:
const dbPromise = idb.open('keyval-store', 1, upgradeDB => {
upgradeDB.createObjectStore('keyval');
});
and would keyval be the name of my variable where I would use keyval.get() or keyval.set() to get and store values?
I decided to move on to the simpler idbKeyval, I'm doing:
app.saveSelectedCities = function() {
var selectedCities = JSON.stringify(app.selectedCities);
idbKeyval.set(selectedCities);
};
instead of the localStorage example:
app.saveSelectedCities = function() {
var selectedCities = JSON.stringify(app.selectedCities);
localStorage.selectedCities = selectedCities;
};
and
app.selectedCities = idbKeyval.keys().then(keys => console.log(keys)).catch(err => console.log('It failed!', err));
instead of the localStorage example:
app.selectedCities = localStorage.selectedCities;
But my app is not loading any data, and in the developer tools console, I get:
app.js:314 Uncaught ReferenceError: idbKeyval is not defined(…)
I'm sure I'm missing something trivial but these are my first steps with javascript and the likes, so please, any help with any of the points touched here would be greatly appreciated!
Given the error you're seeing, it looks like you've forgotten to include the idb-keyval library.
I too was going through this, and wanted it to work with localForage. Took a bit, because I'm new to it too, but here is what I used for the save and load functions which made it all work.
// TODO add saveSelectedCities function here
// Save list of cities to localStorage
app.saveSelectedCities = function() {
var selectedCities = JSON.stringify(app.selectedCities);
localforage.setItem('selectedCities', selectedCities);
//localStorage.selectedCities = selectedCities;
}
localforage.getItem('selectedCities').then(function(cityList) {
app.selectedCities = cityList;
app.selectedCities.forEach(function(city) {
app.getForecast(city.key, city.label);
});
}).catch(function(err) {
app.updateForecastCard(initialWeatherForecast);
app.selectedCities = [
{key: initialWeatherForecast.key, label: initialWeatherForecast.label}
];
app.saveSelectedCities();
});
I'm inside a component, trying to add a newly created entity in an action:
var stakeholding = this.get('store').createRecord('stakeholding', {[...]});
var allCarings = this.get('allCarings');
allCarings.insertAt(0, stakeholding);
But I get this error message:
TypeError: internalModel.getRecord is not a function
allCarings is initialized at page launch like this, inside the component:
this.store.find('stakeholding', {[...]}).then(function(data){
_this.set('allCarings', data);
});
How should I add my entity to the array properly?
You should add record to allCarings array using pushObject:
var stakeholding = this.get('store').createRecord('stakeholding', {[...]});
var allCarings = this.get('allCarings');
allCarings.pushObject(stakeholding);
I'm new to Ember and don't know exactly why but that's what worked for me:
allCarings.insertAt(0, stakeholding._internalModel);