pass object angular js $state.go - javascript

I need to pass my object using $state.go method. my list date is
$scope.oldList = $stateParams.userDetailList;
when console above
console.log($scope.oldList)
data showed correctly. therefor no issue about the data.
now when I call go back function, I need to pass $scope.oldList data to the other page.
my goback function is as below. this function is in (sanction-screening-view page)
$scope.goBack = function () {
$state.go("app.sanction-screening");
};
I need to pass my $scope.oldList object to the "app.sanction-screening" route. how i do it.

The go function can take two parameters:
$state.go('app.sanction-screening', $scope.oldList);

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

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

Transfer data from one html to another using AngularJS services (data share between controllers)

I have looked up several posts with similar issue but was unable to find a solution for my case.
I have a search page that sends a request to the backend an populates the page with search results (each result is an object). I display a concise view of each object and, upon a mouse click on a specific object, the user should be redirected to a page that shows a more detailed view for that object.
On my JS side, I have one controller that handles the $http.post call and retrieves the objects from the backend to display on the first page. I use a different controller for the second page to try and get the relevant object from the first controller (through angular's .service ), but for some reason I get an empty object on the second page. The service works with a getter and a setter. The service is able to set the object just fine, through the first controller, and I am able to print it. However, when redirecting to the second page, while using the second controller's getter, the object gets deleted and shows as empty for some reason.
Here is the relevant code. The service:
app.service('shareService', function(){
var savedData = {}
function set(data) {
savedData = data
console.log(savedData);
}
function get() {
console.log(savedData);
return savedData;
}
return {
set: set,
get: get
}
});
The search (setter) contoller:
app.controller('SearchCtrl', function(shareService, $scope, $http) {
$scope.sendSearch = function() {
$http.post("http://localhost:9080/MedNetApp/rest/mednet/searchCollections", json).success(function (response) {
$scope.collections = response.searchResults;
shareService.set($scope.collections);
});
};
});
The second (getter) controller:
app.controller('CollectionsCtrl', function(shareService, $scope){
$scope.collections = shareService.get();
})
Not sure if this is relevant, but here is also the html part where I set up a temporary test button to redirect to the second page:
<button id=mixing type = "button" class="btn btn-primary-aligned"
data-ng-click = "go('second-page.html')">temp</button>
So, at the end, savedDatashows as empty object when printing it the second time through the get() function. Any idea why this is not working? or a better way to send data to a new page?
EDIT - I should mention that I basically relied on this solution:
AngularJS - Passing data between pages
So, after further research, I came across this solution:
Sharing Data between pages in AngularJS returning empty
I used sessionStorage in my service, as described in the link above, and it fixed the problem.
Use localStorage or sessionStorage
var myJson ={};
localStorage.set("your_Data",myJson);
// to get the value from another page
var returnJson = localStorage.get("Your_Data");

Handling Page Refresh with AngularJS Service and Views

I have a simple SPA with two views: a list view and a detail view. I use a service called StateService to pass data between the two controllers.
I am trying to handle the case where the user refreshes the browser page--when this happens, the StateService gets reinitialized and the detail view can no longer work. I want to detect when this happens and return the user to the list view.
Here is a simplified version of my State Service. The idea is that I would set isInitialized to true when I switch to the detail view so that I can detect when the service has not been properly initialized.
var StateService = function () {
var isInitialized = false;
};
This is what I have tried in the first few lines of my controller. The StateService is being successfully injected into the controller.
//always returns [Object], on refresh or navigating from list page
alert(StateService);
// this next line always returns undefined. Should be false since I am initializing
// the value to false?
alert(StateService.isInitialized);
//One of the many combinations I have tried . . .
if (!StateService.isInitialized | StateService.isInitialized == false) {
$location.path('/');
}
I don't know if this is a gap in my understanding of javascript or angular, but any thoughts on how I can get the above code to work, or better ideas on what to do when a user refreshes the page?
Edit
Using console.log as recommended by nycynik I see the following:
c {} [StateService]
undefined [StateService.isInitialized]
So it seems that StateService itself is just an empty object when this code gets hit. I get the same results from my other controller (the one that handles the list view).
As noted in the comments, the service seems to otherwise work as expected.
I think you have a problem with scoping. variables in javascript have function scope.
isInitialized is scoped only to your StateService Function, so you can't get at it outside of your StateService Function.
not sure exactly how you're getting this thing into your controller, but maybe these help:
if you're using an angular's module.service() to use StateService as a constructor to inject a (new StateService) into your controller then you need to set isInitialized on the instance
var StateService = function () {
this.isInitialized = false;
};
This way (new StateService).isInitialized === false
If you are just using module.factory() or something else that doesn't use new, then you need to put your isInitialized value somewhere else you can actually get at it.
var StateService = function () {
};
StateService.isInitialized = false
Hope that helps.

Categories