Typescript: AngularJS 1 constant issue - angularjs

I am creating an app with TypeScript and AngularJS 1, and I have run into a problem with creating a constant and passing the constant to the other class. I have the following constant in my app:
module app{
export class AUTH_EVENTS {
static get Default():any {
return {
LOGIN_SUCCESS: 'AUTH_EVENTS:LOGIN_SUCCESS',
LOGIN_FAILED: 'AUTH_EVENTS:LOGIN_FAILED',
LOGOUT_SUCCESS: 'AUTH_EVENTS:LOGOUT_SUCCESS',
LOGOUT_FAILED: 'AUTH_EVENTS:LOGOUT_FAILED',
SESSION_TIMEOUT: 'AUTH_EVENTS:SESSION_TIMEOUT',
NOT_AUTHORIZED: 'AUTH_EVENTS:NOT_AUTHORIZED'
};
}
}
var app = getModule();
app.constant("AUTH_EVENTS", AUTH_EVENTS.Default())
}
Which I try to access here:
module app{
class auth{
constructor(public $q: ng.IQService,
public $state:angular.ui.IState,
public AUTH_EVENTS: AUTH_EVENTS){
}
responseError(response:any) {
if (response.status === 401) {
console.log(this.AUTH_EVENTS.LOGIN_SUCCESS);
}
return this.$q.reject(response);
}
}
}
The issue that I have, is that in
console.log(this.AUTH_EVENTS.LOGIN_SUCCESS)
the LOGIN_SUCCESS is not defined.
Do you have any ideas why is this happening? Is there any issue with defining the constant, or is it the issue with the class auth. To be more specific, this is the error that I get when I compile TS into JS:
error TS2339: Property 'LOGIN_SUCCESS' does not exist on type 'AUTH_EVENTS'.

What about this definiton:
module app{
export class AUTH_EVENTS {
LOGIN_SUCCESS= 'AUTH_EVENTS:LOGIN_SUCCESS';
LOGIN_FAILED= 'AUTH_EVENTS:LOGIN_FAILED';
LOGOUT_SUCCESS= 'AUTH_EVENTS:LOGOUT_SUCCESS';
LOGOUT_FAILED= 'AUTH_EVENTS:LOGOUT_FAILED';
SESSION_TIMEOUT= 'AUTH_EVENTS:SESSION_TIMEOUT';
NOT_AUTHORIZED= 'AUTH_EVENTS:NOT_AUTHORIZED';
static Default() { return new AUTH_EVENTS(); }
}
var app = getModule();
app.constant("AUTH_EVENTS", AUTH_EVENTS.Default())
}

Related

mobx observable field for class type isn't working

I am using MobX 6+ in my project and I have a class with an #observable annotated field that contains class type.
I initialize the type with:
class MyClass {
#observable myObservableField = ClassToInitialize;
problemHere() {
....
const MyType = this.myObservableField;
const TypeInstance = new MyType(); // <-- Error is thrown at this line
....
}
}
class ClassToInitialize {
constructor() {
....
}
}
However I get the following error:
Uncaught TypeError: Class constructor IgnoreRegion cannot be invoked without 'new'
After investigating the issue, it appears to happen due to MobX wrapping the field in a proxy function.
In order to solve the issue, use shallow:
class MyClass {
#observable.shallow myObservableField;
....
}

Jhipster webpack compilation error when checking an array value

I am using Jhipster with Angular. I have a method that is trying to check to see if the user in as admin.
import { Component, OnInit } from '#angular/core';
import { ActivatedRoute } from '#angular/router';
import { IPost } from 'app/shared/model/post.model';
import { AccountService } from 'app/core/auth/account.service';
import { Subscription } from 'rxjs';
import { Account } from 'app/core/user/account.model';
#Component({
selector: 'jhi-post-detail',
templateUrl: './post-detail.component.html'
})
export class PostDetailComponent implements OnInit {
post: IPost | null = null;
authSubscription!: Subscription;
account: Account | null = null;
constructor(protected activatedRoute: ActivatedRoute, private accountService: AccountService) { }
ngOnInit(): void {
this.activatedRoute.data.subscribe(({ post }) => (this.post = post));
this.authSubscription = this.accountService.getAuthenticationState().subscribe(account => (this.account = account));
}
previousState(): void {
window.history.back();
}
private isAdmin(): boolean | undefined {
return this.account?.authorities.includes('ROLE_ADMIN');
}
}
When the code is compiled I get an error
ERROR in ./src/main/webapp/app/entities/post/post-detail.component.ts 21:30
Module parse failed: Unexpected token (21:30)
File was processed with these loaders:
* ./node_modules/angular2-template-loader/index.js
* ./node_modules/cache-loader/dist/cjs.js
* ./node_modules/thread-loader/dist/cjs.js
* ./node_modules/ts-loader/index.js
* ./node_modules/eslint-loader/dist/cjs.js
You may need an additional loader to handle the result of these loaders.
| }
| isAdmin() {
> return this.account ? .authorities.includes('ROLE_ADMIN') : ;
| }
| };
ℹ 「wdm」: Failed to compile.
As a workaround, if I just hard-code the return value to 'true' in the isAdmin() method it works and compiles. How come just checking to see if the array contains something causes the webpack to freak out?
Optional chaining was introduced in Typescript 3.7, current JHipster 6.7.1 uses Typescript 3.4.5 so it's not very surprising that your expression is not understood and translated as ternary operator.
Try upgrading typescript version in package.json and npm install to see if it solves it.

TypeScript generics with Angular2 injector

I'm trying to use dependancy injection in angular using an injector. I want to me able to instantiate types at runtime depending on what this component is sent.
#Injectable()
export class ServiceInjectionManager {
private _injector: ReflectiveInjector;
constructor() {
this._injector = ReflectiveInjector.resolveAndCreate([
MockBackend,
BaseRequestOptions,
{
provide: Http,
useFactory: (backendInstance: MockBackend, defaultOptions: BaseRequestOptions) => {
return new Http(backendInstance, defaultOptions);
},
deps: [MockBackend, BaseRequestOptions]
},
AppSettings,
HierarchyService
]);
}
public resolve<T extends HierarchyService>(type:any): T {
return this._injector.get(type);
}
}
I can't seem to find a way to pass a type. I have taken multiple approaches including:
public resolve<T extends HierarchyService>(T): T {
return this._injector.get(T);
}
It seems that generics in TypeScript are not the same as in .NET.

Angularjs ES6 adding filter as class

I am new to es6 and trying to add a filter to an app but keep getting a module not found error. Here's what I have:
index.module.js
...other app imports
import { GlCapitialize } from './filters/glcapitialize';
...
angular.module...(other app controllers, directives, etc)...
.filter('glCapitialize', GlCapitialize);
filter - which is probably completely wrong
export function GlCapitialize(input) {
'ngInject';
return (input, scope)=> {
if (input!=null)
input = input.toLowerCase();
return input.substring(0,1).toUpperCase()+input.substring(1);
}
}

Marionette Module using typescript

How to create marionete module using type script. I saw this how to write marionettejs module using typescript? but its not usefull for my case. I created module like
class TestModule extends Marionette.Module {
constructor(options) {
if (!options)
options = {};
var marionetteApp = new MarionetteApp();
marionetteApp.module("myModule", {
startWithParent: false
});
super("myModule", marionetteApp);
}
}
but its shows error
Unhandled exception at line 3561, column 5 in http://localhost/Scripts/backbone.marionette.js
0x800a138f - JavaScript runtime error: Unable to get property 'initialize' of undefined or null reference
What Im doing wrong. I am new to Marionette and typescript. What is the correct procedure to create marionette module using typescript
My application code is
class MarionetteApp extends Marionette.Application {
headerRegion: Marionette.Region;
leftRegion: Marionette.Region;
centerRegion: Marionette.Region;
constructor() {
super();
this.on("start", this.initializeAfter);
this.addRegions({ headerRegion:"#headerContainer",leftRegion:"#leftContainer",centerRegion:"#centerContainer"});
}
initializeAfter() {
//alert("started")
this.headerRegion.show(new HeaderView());
this.leftRegion.show(new leftView());
this.centerRegion.show(new CenterView());
var MyModule = new TestModule("Test");
//MyModule.start();
}
}
I fixed the issue using following code. Wrapped module inside a class. Its working as expected. Please correct me if I am wrong and anyone knows the correct procedure
class TestModule {
mod: any;
constructor() {
var marionetteApp = new MarionetteApp();
this.mod = marionetteApp.module("myModule", {
startWithParent: false,
initialize: function(){
console.log("initialized");
},
define: function () {
console.log("defined");
}
});
this.mod.on("start", this.onStart);
}
start() {
this.mod.start();
}
onStart() {
console.log("Module started")
}
}
initialization code
var MyModule = new TestModule();
MyModule.start();

Resources