Skip to content

Instantly share code, notes, and snippets.

@radiumrasheed
Created March 13, 2021 13:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save radiumrasheed/3f530497bc20748423653b847afd2963 to your computer and use it in GitHub Desktop.
Save radiumrasheed/3f530497bc20748423653b847afd2963 to your computer and use it in GitHub Desktop.
Simplify components with ts inheritance
import { Injector } from '@angular/core';
export class AppInjector {
private static injector: Injector;
static setInjector(injector: Injector) {
AppInjector.injector = injector;
}
static getInjector(): Injector {
return AppInjector.injector;
}
}
import { noop } from 'rxjs';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { ImportWizardComponent } from '@app/content/management/import-wizard/import-wizard.component';
import { ManagementService } from '@app/content/management/management.service';
import { AppInjector } from '@app/app.injector';
/**
* @interface MajorEntity
*/
export interface MajorEntity {
/**
* The entity to import; must correspond with the API
*/
entity: string;
}
/**
* Extendable class for all bulk import entities
*
* Use like this...
* NewClass extends mixin(Importable)
*
* @implements MajorEntity
*/
export default class Importable implements MajorEntity {
/**
* The entity to import; must correspond with the API
*/
entity: string;
protected modalService: NgbModal;
protected managementService: ManagementService;
/**
* Inject all required services
*/
constructor() {
const injector = AppInjector.getInjector();
this.modalService = injector.get(NgbModal);
this.managementService = injector.get(ManagementService);
}
/**
* Show modal for bulk import wizard
*
* @returns void
*/
importModal() {
const modalRef = this.modalService.open(ImportWizardComponent, {
backdrop: 'static',
beforeDismiss: () => confirm('Are you sure you want to leave this page?')
});
// set the entity
modalRef.componentInstance.entity = this.entity;
modalRef.result
.catch(noop);
}
/**
* Download template for entity
*
* @returns void
*/
downloadTemplate() {
this.managementService.downloadTemplate(this.entity);
}
}
import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from '@app/app.module';
import { environment } from './environments/environment';
import { AppInjector } from '@app/app.injector';
if (environment.production) {
enableProdMode();
}
platformBrowserDynamic().bootstrapModule(AppModule)
.then((moduleRef) => AppInjector.setInjector(moduleRef.injector))
.catch();
@Component({
selector: 'app-user',
templateUrl: './user.component.html'
})
export class UserComponent extends Mixin(Importable) implements OnInit {
users: User[] = [];
entity = 'user';
constructor(
private toastr: ToastrService
) {
super();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment