Why my array is still empty even though I had assign value to this array in my controller? (I am using angularjs, not angular) - angularjs

This question took me one day to debug it, but still no luck.
Problem: this.gridOptions.data = this.allTemplatesFromClassificationRepo ;
**this.allTemplatesFromClassificationRepo ** is still a empty array. Before this line of code executes, I have call activate() function to assign array to **this.allTemplatesFromClassificationRepo **. Please see this line this.allTemplatesFromClassificationRepo = templateReorderProperties;
P.S. Although I cannot get the value of allTemplatesFromClassificationRepo in controller, but I can get the value of it in html.
namespace app.admin {
'use strict';
class FooController {
static $inject: Array<string> = [];
constructor() {
this.activate();
}
activate() {
this.getData();
this.classificationFoo = this.data[0];
this.getTemplateFromGivenRepo(this.classificationFoo.id, this.classificationFoo.displayName);
this.populateData();
}
data: any;
classificationFoo: any;
allDataFromclassificationFoo: any = [];
// demo grid
gridOptions = {
enableFiltering: true,
},
data: []
};
populateData() {
this.gridOptions.data = this.allTemplatesFromClassificationRepo ;
}
getData() {
this.fooService.getUserData();
this.data = this.fooService.userdata;
}
getTemplateFromGivenRepo(fooId: string, fooName: string) {
switch (fooId) {
case 'FOO':
this.TemplateApi.templatesAvaiableForRepoIdGET(fooId).then(data => {
data.forEach(element => {
element.fooName = fooName;
});
let templateReorderProperties = data
this.allTemplatesFromClassificationRepo = templateReorderProperties;
}, error => {
});
break;
default:
break;
}
};
}
class Bar implements ng.IDirective {
static $inject: Array<string> = [];
constructor() {
}
bindToController: boolean = true;
controller = FooController;
controllerAs: string = 'vm';
templateUrl: string = 'app/foo.html';
static instance(): ng.IDirective {
return new Bar();
}
}
angular
.module('app.admin')
.directive('bar', Bar.instance);
}

getTemplateFromGivenRepo is async operation.
Move this.populateGridData(); call inside getTemplateFromGivenRepo after
this.allTemplatesFromClassificationRepo = templateReorderProperties;
getTemplateFromGivenRepo(repoId: string, repoName: string) {
switch (repoId) {
case 'CLASSIFICATION':
this.TemplateApi.templatesAvaiableForRepoIdGET(repoId).then(data => {
this.allTemplatesFromClassificationRepo = templateReorderProperties;
this.populateGridData(); // call here
}, error => {
});
}
};
OR
You can return promise from getTemplateFromGivenRepo and in then able success callback,call
this.populateGridData();

I think the problem is in this instance that different inside Promise resolve.
Try to write in beginning something like:
var self = this;
and after that change all this to self key.
a.e.:
self.gridOptions.data = self.allTemplatesFromClassificationRepo;
// and so on ...
By this way you will guarantee that you use same scope instance
Hope it will work

Related

Ionic 4: 'Typescript error' in helperService Cannot read property 'length' of undefined at HelperService

Getting error 'Cannot read property 'length' of undefined at HelperService.addCommasToArray' when trying to loop through an array that has been passed as a paramter in a helperService class [Typescript]
I'm really not sure why this is not working - I believe it should be straightforward - all I'm trying to do is pass in an array as a parameter and add a ',' to every value in the array (except the last value)
Here is my HelperService Class method:
export class HelperService {
constructor() { }
/*
* Add commas to every value in the array except for the last value
*/
addCommasToArray(array: Array<any>) : Array<any> {
for (let i = 0; array.length; i++){
array[i] += ", ";
}
return array;
}
}
I then call this method within the ngInit of another ts class
this.helperService.addCommasToArray(this.previousClubs);
Here is the ngInit method
public previousClubs: Array<any>;
constructor(private playersService: PlayersService,private
helperService: HelperService, private route: ActivatedRoute) { }
ngOnInit() {
const playerId: string = this.route.snapshot.paramMap.get('id');
this.playersService.getPlayerDetails(playerId).get()
.then(playerDetailsSnapshot=> {
this.currentPlayerDetails = playerDetailsSnapshot.data();
this.currentPlayerDetails.id = playerDetailsSnapshot.id;
});
/*
* Return Previous Clubs
*/
this.playersService.getPreviousClubs(playerId).get().then(
previousClubsSnapshot =>{
this.previousClubs = [];
previousClubsSnapshot.forEach(snap => {
this.previousClubs.push({
id: snap.id,
name: snap.data().name,
});
return false;
});
});
this.helperService.addCommasToArray(this.previousClubs);
}
so here:
this.playersService.getPreviousClubs(playerId).get().then(
previousClubsSnapshot =>{
this.previousClubs = [];
previousClubsSnapshot.forEach(snap => {
this.previousClubs.push({
id: snap.id,
name: snap.data().name,
});
return false;
});
});
// this line executes without awaiting for .then enclosed scope
this.helperService.addCommasToArray(this.previousClubs);
Basically you call addCommasToArray even before your previousClubs var gets array assigned to it and then gets all its items pushed in. To fix since your method is (.then) async you need to call for this method inside the .then execution scope:
ngOnInit() {
const playerId: string = this.route.snapshot.paramMap.get('id');
this.playersService.getPlayerDetails(playerId).get()
.then(playerDetailsSnapshot=> {
this.currentPlayerDetails = playerDetailsSnapshot.data();
this.currentPlayerDetails.id = playerDetailsSnapshot.id;
});
/*
* Return Previous Clubs
*/
this.playersService.getPreviousClubs(playerId).get().then(
previousClubsSnapshot =>{
this.previousClubs = [];
previousClubsSnapshot.forEach(snap => {
this.previousClubs.push({
id: snap.id,
name: snap.data().name,
});
return false;
});
});
this.helperService.addCommasToArray(this.previousClubs);
}

ngShow expression is evaluated too early

I have a angular component and controller that look like this:
export class MyController{
static $inject = [MyService.serviceId];
public elements: Array<string>;
public errorReceived : boolean;
private elementsService: MyService;
constructor(private $elementsService: MyService) {
this.errorReceived = false;
this.elementsService= $elementsService;
}
public $onInit = () => {
this.elements = this.getElements();
console.log("tiles: " + this.elements);
}
private getElements(): Array<string> {
let result: Array<string> = [];
this.elementsService.getElements().then((response) => {
result = response.data;
console.log(result);
}).catch(() => {
this.errorReceived = true;
});
console.log(result);
return result;
}
}
export class MyComponent implements ng.IComponentOptions {
static componentId = 'myId';
controller = MyController;
controllerAs = 'vm';
templateUrl = $partial => $partial.getPath('site.html');
}
MyService implementation looks like this:
export class MyService {
static serviceId = 'myService';
private http: ng.IHttpService;
constructor(private $http: ng.IHttpService) {
this.http = $http;
}
public getElements(): ng.IPromise<{}> {
return this.http.get('./rest/elements');
}
}
The problem that I face is that the array elements contains an empty array after the call of onInit(). However, later, I see that data was received since the success function in getELements() is called and the elements are written to the console.
elements I used in my template to decide whether a specific element should be shown:
<div>
<elements ng-show="vm.elements.indexOf('A') != -1"></elements>
</div>
The problem now is that vm.elements first contains an empty array, and only later, the array is filled with the actual value. But then this expression in the template has already been evaluated. How can I change that?
Your current implementation doesn't make sense. You need to understand how promises and asynchronous constructs work in this language in order to achieve your goal. Fortunately this isn't too hard.
The problem with your current implementation is that your init method immediately returns an empty array. It doesn't return the result of the service call so the property in your controller is simply bound again to an empty array which is not what you want.
Consider the following instead:
export class MyController {
elements: string[] = [];
$onInit = () => {
this.getElements()
.then(elements => {
this.elements = elements;
});
};
getElements() {
return this.elementsService
.getElements()
.then(response => response.data)
.catch(() => {
this.errorReceived = true;
});
}
}
You can make this more readable by leveraging async/await
export class MyController {
elements: string[] = [];
$onInit = async () => {
this.elements = await this.getElements();
};
async getElements() {
try {
const {data} = await this.elementsService.getElements();
return data;
}
catch {
this.errorReceived = true;
}
}
}
Notice how the above enables the use of standard try/catch syntax. This is one of the many advantages of async/await.
One more thing worth noting is that your data services should unwrap the response, the data property, and return that so that your controller is not concerned with the semantics of the HTTP service.

Can't access this from $http callback

I'm using angular 1.5 with typescript, I can't access this property from the callback being returned from $http promise.
When I'm trying to access a private method from the callback 'this' is undefined
I have the following ServerAPI service:
export class ServerAPI implements IServerAPI {
static $inject:Array<string> = ['$http', '$q'];
constructor(private $http:ng.IHttpService,
private $q:ng.IQService) {
}
postHandler(partialUrl:string, data?:any, config?:any):ng.IPromise<any> {
let url = this.buildUrl(partialUrl);
var result:ng.IPromise< any > = this.$http.post(url, data, config)
.then((response:any):ng.IPromise<any> => this.handlerResponded(response, data))
.catch((error:any):ng.IPromise<any> => this.handlerError(error, data));
return result;
}
private handlerResponded(response:any, params:any):any {
response.data.requestParams = params;
return response.data;
}
private handlerError(error:any, params:any):any {
error.requestParams = params;
return error;
}
}
Which been consumed by user.service:
export class UserService implements IUserService {
static $inject:Array<string> = ['$q', 'serverAPI'];
constructor(private $q:ng.IQService,
private serverAPI:blocks.serverAPI.ServerAPI) {
var vm = this;
$rootScope.globals = $rootScope.globals || {};
$rootScope.globals.currentUser = JSON.parse($window.localStorage.getItem('currentUser')) || null;
this.getUserPermissions();
}
private getUserPermissions:() => IPromise<any> = () => {
var promise = this.serverAPI.postHandler('MetaDataService/GetUserPermissions',
{userID: this.getUser().profile.UserID})
.then((res) => {
this.updateUser('permissions', res.GetUserPermissionsResult); // NOT WORKING, this is undefined
})
.catch((response:any):ng.IPromise<any> => {
this.updateUser('permissions', res.GetUserPermissionsResult); // NOT WORKING, this is undefined
});
return promise;
};
private updateUser:(property:string, value:any) => void = (property, value) => {
};
}
The issue is this line:
.then((response:any):ng.IPromise<any> => this.handlerResponded(response, data))
While your lexical scope is maintained in order to find the handlerResponded method the scope is not fully preserved in the output.
you can get around this in 2 ways:
inline your handler function rather than have it as a function on your class
you can bind the call to handlerResponded to the instance
example of binding:
.then((response:any):ng.IPromise<any> => this.handlerResponded(response, data).bind(this))

My service is returning the function's text and not an object

I have a service to share an object in my app... I want to post that object to the mongo db but when I call the function that should return the object it gives me the function's text.
The service is here:
angular.module('comhubApp')
.service('markerService', function () {
this.markers = [];
this.newMarker = { title: '',
description: '',
lat: '',
lon: '',
user: '',
created_at: '' };
// This is supposed to return the marker object
this.newMarker = function () {
return this.newMarker;
};
this.setTitle = function (title) {
this.newMarker.title = title;
console.log('title service set: ' + title);
};
this.setDescription = function (description) {
this.newMarker.description = description;
console.log('Description service set: ' + description);
};
this.setLat = function (lat) {
this.newMarker.lat = lat;
console.log('lat service set: ' + lat);
};
this.setLon = function (lon) {
this.newMarker.lon = lon;
console.log('lon service set: ' + lon);
};
this.reset = function () {
this.newMarker = { title: '',
description: '',
lat: '',
lon: '',
user: '',
created_at: ''};
}
this.setMarkers = function (markers) {
this.markers = markers;
}
this.markers = function () {
return this.markers;
}
this.addMarker = function (marker) {
//todo append marker
}
});
newMarker returns:
this.newMarker = function () {
return this.newMarker;
};
The Controller using the service is here
$scope.addMarker = function() {
if($scope.newMarker.title === '') {
console.log('newMarker title is empty');
return;
}
markerService.setTitle($scope.newMarker.title);
markerService.setDescription($scope.newMarker.description);
console.log(markerService.newMarker());
// $http.post('/api/markers', { name: $scope.newMarker });
// $scope.newMarker = '';
};
$scope new marker is form data.. i tried to put that right into my service with no success. Instead I out the form data into the controller then push it to the service. If there is a better way to do that please let me know.
If this service is bad in any other way let me know I am new to all this and so I followed another answer I saw on here.
You are overriding your object with function. Just give them different names and it should work just fine.
this.newMarker = { ... };
this.getNewMarker = function () { return this.newMarker };
EDIT:
You should also always create new instance from marker. Otherwise you just edit the same object all the time. Here is example I made. Its not best practice but hope you get the point.
angular.module('serviceApp', [])
.factory('Marker', function () {
function Marker() {
this.title = '';
this.descrpition = '';
}
// use setters and getters if you want to make your variable private
// in this example we are not using these functions
Marker.prototype.setTitle = function (title) {
this.title = title;
};
Marker.prototype.setDescription = function (description) {
this.description = description;
};
return Marker;
})
.service('markerService', function (Marker) {
this.markers = [];
this.getNewMarker = function () {
return new Marker();
}
this.addMarker = function (marker) {
this.markers.push(marker);
}
})
.controller('ServiceCtrl', function ($scope, markerService) {
$scope.marker = markerService.getNewMarker();
$scope.addMarker = function () {
markerService.addMarker($scope.marker);
$scope.marker = markerService.getNewMarker();
}
$scope.markers = markerService.markers;
});
You could also create Marker in controller and use markerService just to store your object.
And working demo:
http://jsfiddle.net/3cvc9rrs/
So, that function is the problem. I was blindly following another example and it was wrong in my case. The solution is to remove that function and access markerService.newMarker directly.
I am still a big enough noob that I am not sure why the call was returning the function as a string. It seems to have something to do with how it is named but it is just a guess.

What type of Typescript return value should I use for a $http call that returns nothing other than success?

I created a service using Typescript:
class ConfigService implements IConfigService {
public admin = {};
public adminBackup = {};
public user = {};
public loaded = false;
constructor(
private $http: ng.IHttpService,
private $q: ng.IQService
) {
}
static $inject = [
'$http',
'$q'
];
put = ():ng.IHttpPromise<> => {
var defer = this.$q.defer();
if (angular.equals(this.admin, this.adminBackup)) {
return defer.resolve();
} else {
this.$http({
data: {
adminJSON: JSON.stringify(this.admin),
userJSON: JSON.stringify(this.user)
},
url: '/api/Config/Put',
method: "PUT"
})
.success(function (data) {
this.adminBackup = angular.copy(this.admin);
this.userBackup = angular.copy(this.user)
return defer.resolve();
});
}
return defer.promise;
};
}
I also created this interface:
interface IConfigService {
put(): ng.IHttpPromise<>;
}
However the code is giving me an error saying:
Error 3 Cannot convert 'void' to 'ng.IHttpPromise<any>'.
Error 4 Cannot convert 'ng.IPromise<{}>' to 'ng.IHttpPromise<any>':
Type 'ng.IPromise<{}>' is missing property 'success' from type 'ng.IHttpPromise<any>'.
Use
ng.IPromise<void>
Also you could let it implicitly type it for you if you don't declare a return type and don't use that interface.
Also there should be no return statement here :
return defer.resolve();
Just :
defer.resolve();
When I ran into this issue I found that I wasn't able to use ng.IPromise<void> as the declarations for ng.IHttpPromise<> demanded that I return an object.
For example:
public saveTechnicianNote = (jobNumber: string, technicianNote: Model.TechnicianNote): ng.IPromise<void> => {
var data = {
jobNumber: jobNumber,
subject: technicianNote.subject,
details: technicianNote.details
};
return this.$http.post(this.urlFactory.saveTechnicianNote, data);
}
threw up an error that Type IHttpPromise<{}> is not assignable to IPromise<void>.
To get around this I made it return ng.IPromise<any>. Not 100% ideal but it was the best solution I could come up with that didn't require me to extend on angular.d.ts
Final Code:
public saveTechnicianNote = (jobNumber: string, technicianNote: Model.TechnicianNote): ng.IPromise<any> => {
var data = {
jobNumber: jobNumber,
subject: technicianNote.subject,
details: technicianNote.details
};
return this.$http.post(this.urlFactory.saveTechnicianNote, data);
}

Resources