map in array not working in ngOnChange event Angular 5 - javascript

I am new to Angular and this is my first app. I have a parent component which gets data from an API using service. With the response from the service, I create an array and pass it as attribute to a child component. In the child component, I have the follow ngOnChange event
ngOnChanges(changes: any) {
console.log("Mode total in mode", this.modeTotal);
this.modeTotal.map(mode => {
console.log("For each");
this.doughnutChartLabels.push(mode.name);
this.doughnutChartData.push(mode.total);
console.log(`Loop inside onChange Name: ${mode.name} and Total: ${mode.total}`);
});
console.log("DoughnutChartLabels", this.doughnutChartLabels);
console.log("DoughnutChartData", this.doughnutChartData);
}
The problem I am facing is the console above and below the map function is working, printing the content of modeTotal, doughnutChartLabels and doughnutChartData but not the string inside the map function. And the modeTotal has the array of data which I expect to be returned.
What am I missing?
Note: I push data into the modeTotal from another component which receives data from an API. The modeTotal is not getting updated even when new data is pushed into it.

The change event will not occur on an array when a new data is pushed into it since the variable is referring to the same object. Try adding a local variable to monitor the push changes.

Related

Angular Http subscribe - cannot assign to variable in component

I want to retrieve data from api and assign it to some value inside the angular component. In subscribe I'm trying to assign the data to loggedUser and then call function inside this subscribe to navigate to another component with this received object. Unfortunately I got the error : The requested path contains undefined segment at index 1. I want to have this object set outside the subscribe too. How can I achieve this?
logIn() {
this.portfolioAppService.logIn(this.loggingUser).subscribe((data) => {
this.loggedUser = data;
console.log(this.loggedUser);
console.log(data);
this.navigateToProfile(this.loggedUser.Id);
});
}
navigateToProfile(id: number) {
this.router.navigate(['/profile', id]);
}
console output
You are using an incorrectly named property when calling navigateToProfile.
From your console output, I can see that the data object in the subscribe looks like this:
{
id: 35,
// ..
}
But you are calling the function like this:
this.navigateToProfile(this.loggedUser.Id);
Instead, use the property id (lower case)
this.navigateToProfile(this.loggedUser.id);
To narrow this problem down in the future, try being more specific in your testing. Humans are good at seeing what they want to see and will assume the problem is more complicated than it is. If you had tried console.log(this.loggedUser.Id), you would have seen the result undefined, and worked out the problem yourself.

Angular - cannot access items in the database through the methods in the component which should be called when the page loads

In my service file, I have a get method to return data form a collection to an array. I want to have another method in my component (front-end controller) which need to access those data from the data base before the page loads. So I use it like below (books is the array to store data from the database)
refreshBookList() {
this.bookService.getBookList().subscribe((res) => {
this.books = res as Book[];
console.log(this.books);});
}
I need to do this when the page loads. so I call it like
ngOnInit() {
this.refreshBookList();
}
But it only returns an empty array. The data gets added to the array only if the method is called from a button click in the interface. Is there any way I could get the result at page initialization.
Maybe you can try to call the method inside AfterViewInit

unable to view new table data after concat - Ionic 3 Angular 4

I'm using ionic's events to pass data from page to page. In this instance I'm passing an array to another page, let's say with two objects. The data I'm wanting to add to is called dataOne and I'm using a life cycle function so that when the user enters the page they will be automatically tested from this function whether or not there is an event to be concatenated onto dataOne. The issue is, the data isn't being added. I'm able to retrieve the data but nothing happens to the table, as I'm still getting the same result.
ts
ionViewWillEnter(){
this.events.subscribe('market', (dataTwo) => {
return this.dataOne = this.dataOne.concat(dataTwo)
})
}
What is 'Market' ? dataOne is array? In my opinion,
dataOne: any[]=[];
...
this.events.subscribe((dataTwo) =>{
this.dataOne.push(dataTwo.market); // if market you want to catch data
}

How to bind Json data returned by a asynchronous call to a knockout observableArray correctly

I am trying to get a json object by an ajax call, and put it into a knockout observable.
var self = this;
this.arnVal = ko.observableArray([]);
var promise = $.getJSON('../../url/to/my/api');
promise.done(function(data) {
console.log(data);
console.log(data["metricValues"]);
self.arnVal().push(data["metricValues"]);
console.log(self.arnVal());
});
The expected values are getting printed correctly by the console logs inside the promise.done() function call. That is, the data is in the correct Array format expected by the Oracle Jet component I am binding it with.
This code is in a Knockout component javascript file, which I am using in a HTML file somewhere else as a part of a Knockout component.
In the HTML file of the component, I am using arnVal to populate a Oracle Jet chart.
But the chart never gets populated with the updated arnVal data as obtained from the getJSON call.
What am I doing wrong?
Just remove the extra parens from self.arnVal().push(...).
self.arnVal.push(data["metricValues"]);
Currently the parens are unboxing the observable array and pushing the new item to the underlying javascript array. This bypasses knockout's event triggers.
Remove the parenthesis here:
self.arnVal().push(data["metricValues"]);
//^^ here
See the spec: http://knockoutjs.com/documentation/observableArrays.html
var myObservableArray = ko.observableArray(); // Initially an empty array
myObservableArray.push('Some value'); // Adds the value and notifies observers
The reason is self.arnVal is an observable array while self.arnVal() is a simple array (which does not have notification capabilities).

How do I pass an object data as a value (not as reference) using angularJS $broadcast

I'm trying to pass some data and action within two controllers by using AngularJS $broadcast event. But I'd problems with passing the data as a value (not reference).
What I've done so far is first I created a function that broadcast sendCartPreview event with an object of shoppingCart inside shopping-cart.controller.js
//function inside shopping-cart.controller.js
function sendCartPreview() {
var shoppingCart = $scope.shoppingCart;
$rootScope.$broadcast('sendCartPreview', shoppingCart);
}
Then I add a listener of the event on another controller which retrieve the shoppingCart data and pass the data value to sendCartPreview function inside the controller
//function inside chat.controller.js
$scope.$on("sendCartPreview", function(event, message){
sendCartPreview(message);
})
Basically the sendCartPreview function received the object data and added it to an array of message.
function sendCartPreview(shopping_cart) {
//some logic here and push the data to an array
vm.arrayOfMessage.push(shopping_cart);
}
The problem that I'm facing is whenever $scope.shoppingCart value changes, the value inside vm.arrayOfMessage also change according to the respective changes. What I want to achieve in the mean time is passing the data as a value (not by reference) so that everytime $scope.shoppingCart value changed, it will not affect the data inside vm.arrayOfMessage. How do I achieve that? Kindly need your help in this, any kind of help would be appreciated, thanks!
Make a deep copy call like sendCartPreview(angular.copy(message));
Thats pretty easy. I assume you have jquery also.
var cart = jQuery.extend(true, {}, shoppingCart);
& broadcast cart.
You can use angular.copy, for more info: https://docs.angularjs.org/api/ng/function/angular.copy

Categories