How to refresh Graph Input data in Angular 2 - angularjs

I am using some Graph view to view some statistic in my project.
e.g. Morish Grapgh, Pie chart graph.
I have an option like date range, so that I can specify the range of date and can fetch the data within that range and show the output graph in the front end.
The issue I am facing is at the First time I am able to see the out put while I am changing the Date range.
from the second time I am able to get the Data from the backend but after setting the new set of values to the graph Data, but the graph view is not changing because the graph is not able to refresh.
Here sample code. Please ask if any additional info needed.
<sa-morris-graph *ngIf="graphData!=null" [data]="graphData"
type="area"
[options]="{
xkey: 'x',
ykeys: ['y', 'z'],
labels: ['USER', 'New USER']
}"></sa-morris-graph>
from the Component type script file I am setting graphData
export class GAUserComponent implements OnInit{
fromDate : any ;
toDate : any ;
graphData : any = null;
dateSelected(){
this.gaService.getGaData(this.req,"/users")
.subscribe(
data => {
this.dataResponse = data;
let grData = [];
for (let data of this.dataResponse.usersByDate) {
var sample={"x": data.valueX ,"y": data.valueY , "z" : data.valueZ };
grData.push(sample);
}
this.graphData = grData;
},
err => {
console.log("Error occered : "+ err);
}
);
}
Please suggest me to solve the problem.
I guess In angular 1 there is a watch() to achieve this but in angular 2 this function is not there.
correct me If I am wrong and help me solve this
Thanks

Related

AJax issue while loading google chart in react

I am trying to use Google chart in React. I read the data from the database and use hook(useState) to save the data. But I can't load the google chart when I fetch the data. I guess it is Ajax problem. I have tried to copy the data that I read from console.log and paste it, it works, so it is not the data format issue.
//inistialise
const [v1, setV1] = useState(['x','sensor'],[0,0])
//define data value
const data = v1;
//define option for Chart
const options = {
title: "Box Office Earnings in First Two Weeks of Opening",
subtitle: "in millions of dollars (USD)",
interpolateNulls: true
};
//fetch data from database and change the data format
async function getAllSensorProfile(sensorIdList, sensorSubId, starttime, endtime) {
sensorIdList = JSON.stringify(sensorIdList)
await deviceService.GetTimeSeriesListBySensorIdListTimeRange(sensorIdList, sensorSubId, starttime, endtime).then(
(result) => {
var time = []
var _v1 = [['x', 'dogs']]
result.map((str) => (
str[1] = parseFloat(str[1])
))
_v1 = _v1.concat(result)
setV1(JSON.stringify(_v1))
console.log(v1)
},
error => {
console.log(error)
}
)
}
<Chart
chartType="LineChart"
data={this.state.data}
options={options}
width={"70%"}
height={"400px"}
/>
I have fixed it! OMG I had this issue for a few days but could not fix it. Now I find the problem!
So the problem is, setV1(JSON.stringfy(_v1)) is converting v1 to be a string, however, in <Chart>, data={data} only accept object, not a string.
So, I simply just change it to setV1(_v1) then it works!

How to refresh both data and categoryAxis in Kendo Chart?

I have a problem in AngularJS + TS when it comes to refreshing the data and axis in Kendo chart.
There are 3 problems:
.refresh() and .redraw() didn't exist,
Data not refreshing,
Category Axis (X axis) not refreshing.
How to be able to use .refresh() etc. and then be able to change both data & X axis, when a new data is pushed?
I was dealing with it for few days (as a Junior BACKEND dev...), so I want to share my solution with you :)
TypeScript
First, you need to do "helper" field called "chart", with Partial to properly deal with optional ('myField?').
Probably you've got just .ChartOptions,
chartOptions: kendo.dataviz.ui.ChartOptions;
but only .Chart has .refresh() method, so create new field called chart:
chart: Partial<kendo.dataviz.ui.Chart>;
and in the initialization method of your chart, do an observable from dataSource in your chartOptions:
this.chartOptions = {
// Other fields of the chartOptions
dataSource: new kendo.data.DataSource({
transport: {
read: (options) => {
// Your logic to create new data array
options.success(yourNewData);
}
}})
};
}
and then create new method (refresh), that should look like this:
this.chartOptions.dataSource.read();
'labels' in this.chart.options.categoryAxis ? this.chart.options.categoryAxis.labels.step = step : null;
this.chart.refresh();
HTML:
(remember to set options from chartOptions, not .chart.options, because you cannot get options from non-existing object.)
<div>
<div kendo-chart="$ctrl.chart" k-options="$ctrl.chartOptions"></div>
</div>
Also remember, when you close your chart (eg. by ng-if), then you need to run init function again, because refresh function would throw an error about "undefined".

Filter data by user with angularfire

I'm using angular-ui-fullcalendar to show and edit events. Users can log in and have unique uid when logged in. I want to use this to distinguish events made by current user from other events. I want to give current user events another backgroundColor.
What is the best way to do this??
I tried several things. My data looks like this:
```
database
bookings
-KWnAYjnYEAeErpvGg0-
end: "2016-11-16T12:00:00"
start: "2016-11-16T10:00:00"
stick: true
title: "Brugernavn Her"
uid: "1f17fc37-2a28-4c24-8526-3882f59849e9"
```
I tried to filter all data with current user uid like this
var ref = firebase.database().ref().child("bookings");
var query = ref.orderByChild("uid").equalTo(currentAuth.uid);
var bookings = $firebaseArray(query);
$scope.eventSources = [bookings];
This doesn't return anything. If I omit the filter in line 2 it returns all bookings as expected. But even if the filter worked it would not solve my problem, because I want to fetch both current user events and all other events. Firebase does not have a "not equal to" filter option...
I tried to loop through each record and compare uids and setting backgroundColor if condition was met:
var ref = firebase.database().ref().child("bookings");
var bookings = $firebaseArray(ref);
bookings.$ref().on("value", function(snapshot) {
var list = snapshot.val();
for (var obj in list) {
if ( !list.hasOwnProperty(obj) ) continue;
var b = list[obj];
if (b.uid === currentAuth.uid) {
b.className = "myBooking";
b.backgroundColor = "red";
}
}
});
$scope.eventSources = [bookings];
But this causes asynchronous problems so the 'bookings' array assigned to $scope.eventSources wasn't modified. I tried to move the $scope.eventSources = [bookings] inside the async code block but FullCalendar apparently can't handle that and renders nothing.
I also tried this but no luck either:
bookings.$loaded()
.then(function(data) {
$scope.eventSources = [data];
})
.catch(function(error) {
console.log("Error:", error);
});
What is the best solution to my problem?
If you're looking to modify the data that is loaded/synchronized from Firebase, you should extend the $firebaseArray service. Doing this through $loaded() is wrong, since that will only trigger for initial data.
See the AngularFire documentation on Extending $firebaseArray and Kato's answer on Joining data between paths based on id using AngularFire for examples.

UI not updating after ajax fetch

I have this code for a restaurant app:
// Select date and load resources
$scope.selectDate = function (date) {
$scope.dateInActiveSelection = date;
loadMenuFor(date);
};
// Load daily menu for given date.
function loadMenuFor (date) {
DataApi.dailyMenu(date, function (response) {
console.log('Loaded menu for ' + date.toString());
$scope.menuItems = $scope.originalMenuItems = response.data;
});
}
I am fetching new menu for every day the user selects with this method:
// Select date and load resources
$scope.selectDate = function (date) {
$scope.dateInActiveSelection = date;
loadMenuFor(date);
};
But the UI isn't updating. I have one {{ menuItems.length }} displayed and another ng-repeat neither of which are getting updated.
I tried $scope.$apply() as mentioned in other answers but I get a in-progress error, even when I try it inside a $timeout.
Where am I going wrong ?
I found out the problem. There were two elements with the asking for the same controller. One was the date chooser element and another was the one with the item listing. So, whenever I was choosing the date, the scope was getting changed.

Pagination not working with Firebase scroll reference

This is probably a noob question but I am following this firebase util
scroll ref pagination to retrieve my data from firebase database. I want to receive only those objects that meet the criteria of user city but its not working as I am not receiving anything in return.
The code I am trying is
var baseRef = new Firebase("https://myfirebaseurl.firebaseio.com");
var norm = new Firebase.util.NormalizedCollection(
baseRef.child('Events') // the master index
);
// filter the client-side results to only include records where event_city matches user city
norm = norm.filter(function(data, key, priority) {
return data.event_city === $rootScope.userCity; // setting $rootScope.userCity initially
});
// specify the fields for each path
norm = norm.select( 'Events.lat', 'Events.lng', 'Events.event_city', 'Events.event_state' );
var ref = norm.ref();
var scrollRef = new Firebase.util.Scroll(ref,"event_city");
$rootScope.events= $firebaseArray(scrollRef);
// load the first ten events
scrollRef.scroll.next(10);
`
My Firebase structure is really simple
root :
Events :{
-Event1-id :{
created_on: 225325223,
event_state: "abc",
event_city:"äbc",
event_desc:"abd",
lat : 28.1234567, //event latitude
lng : 77.1234567, //event longitude
event_address : "abc",
event_date : 446343643
},
-Event2-id:{
.....
},
-Event3-id:{
}....
}
Please help me out. Sorry this is my first question here so let me know if anything else is required.

Resources