Skip to content

Commit

Permalink
[Angular] Angular DI: Using Inject instead of Constructor (part 2)
Browse files Browse the repository at this point in the history
  • Loading branch information
qmonmert committed Dec 17, 2023
1 parent 436e352 commit 55e16f9
Show file tree
Hide file tree
Showing 9 changed files with 70 additions and 58 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
See the License for the specific language governing permissions and
limitations under the License.
-%>
import { Component, AfterViewInit, ElementRef, ViewChild } from '@angular/core';
import { Component, AfterViewInit, ElementRef, inject, ViewChild } from '@angular/core';
import { FormBuilder, FormsModule, ReactiveFormsModule, Validators } from '@angular/forms';
import SharedModule from 'app/shared/shared.module';

Expand All @@ -33,11 +33,16 @@ export default class PasswordResetInitComponent implements AfterViewInit {
email?: ElementRef;

success = false;
resetRequestForm = this.fb.group({
email: ['', [Validators.required, Validators.minLength(5), Validators.maxLength(254), Validators.email]],
});
resetRequestForm;

constructor(private passwordResetInitService: PasswordResetInitService, private fb: FormBuilder) {}
private passwordResetInitService = inject(PasswordResetInitService);
private fb = inject(FormBuilder);

constructor() {
this.resetRequestForm = this.fb.group({
email: ['', [Validators.required, Validators.minLength(5), Validators.maxLength(254), Validators.email]],
});
}

ngAfterViewInit(): void {
if (this.email) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
See the License for the specific language governing permissions and
limitations under the License.
-%>
import { Component } from '@angular/core';
import { Component, inject } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';

Expand All @@ -33,7 +33,8 @@ import { ITEM_DELETED_EVENT } from 'app/config/navigation.constants';
export class <%= entityAngularName %>DeleteDialogComponent {
<%= entityInstance %>?: I<%= entityAngularName %>;

constructor(protected <%= entityInstance %>Service: <%= entityAngularName %>Service, protected activeModal: NgbActiveModal) {}
protected <%= entityInstance %>Service = inject(<%= entityAngularName %>Service);
protected activeModal = inject(NgbActiveModal);

cancel(): void {
this.activeModal.dismiss();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
See the License for the specific language governing permissions and
limitations under the License.
-%>
import { Component, Input } from '@angular/core';
import { Component, inject, Input } from '@angular/core';
import { ActivatedRoute, RouterModule } from '@angular/router';

import SharedModule from 'app/shared/shared.module';
Expand All @@ -35,12 +35,10 @@ import { DataUtils } from 'app/core/util/data-util.service';
export class <%= entityAngularName %>DetailComponent {
@Input() <%= entityInstance %>: I<%= entityAngularName %> | null = null;

constructor(
<%_ if (anyFieldIsBlobDerived) { _%>
protected dataUtils: DataUtils,
protected dataUtils = inject(DataUtils);
<%_ } _%>
protected activatedRoute: ActivatedRoute
) {}
protected activatedRoute = inject(ActivatedRoute);

<%_ if (anyFieldIsBlobDerived) { _%>
byteSize(base64String: string): string {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@

const componentName = entityAngularName + 'Component';
_%>
import { Component, OnInit } from '@angular/core';
import { Component, inject, OnInit } from '@angular/core';
<%_ if (!paginationNo) { _%>
import { HttpHeaders } from '@angular/common/http';
<%_ } _%>
Expand Down Expand Up @@ -139,22 +139,20 @@ export class <%= componentName %> implements OnInit {
<%- include('infinite-scroll-template'); -%>
<%_ } _%>

constructor(
protected <%= entityInstance %>Service: <%= entityAngularName %>Service,
protected activatedRoute: ActivatedRoute,
public router: Router,
public router = inject(Router);
protected <%= entityInstance %>Service = inject(<%= entityAngularName %>Service);
protected activatedRoute = inject(ActivatedRoute);
<%_ if (paginationNo) { _%>
protected sortService: SortService,
protected sortService = inject(SortService);
<%_ } else if (paginationInfiniteScroll) { _%>
protected parseLinks: ParseLinks,
protected parseLinks = inject(ParseLinks);
<%_ } _%>
<%_ if (anyFieldIsBlobDerived) { _%>
protected dataUtils: DataUtils,
protected dataUtils = inject(DataUtils);
<%_ } _%>
<%_ if (!readOnly) { _%>
protected modalService: NgbModal
protected modalService = inject(NgbModal);
<%_ } _%>
) {}

<%_ if (paginationInfiniteScroll) { _%>
reset(): void {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ if (paginationPagination || paginationInfiniteScroll) {
searchType = 'SearchWithPagination';
}
_%>
import { Injectable } from '@angular/core';
import { inject, Injectable } from '@angular/core';
import { HttpClient, HttpResponse } from '@angular/common/http';
import { Observable<%_ if (searchEngineAny) { _%>, asapScheduler, scheduled<%_ } _%> } from 'rxjs';

Expand Down Expand Up @@ -75,13 +75,14 @@ export type EntityArrayResponseType = HttpResponse<I<%= entityAngularName %>[]>;

@Injectable({ providedIn: 'root' })
export class <%= entityAngularName %>Service {
protected http = inject(HttpClient);
protected applicationConfigService = inject(ApplicationConfigService);

protected resourceUrl = this.applicationConfigService.getEndpointFor('api/<%= entityApiUrl %>'<% if ((applicationTypeGateway || applicationTypeMicroservice) && locals.microserviceName) { %>, '<%= microserviceName.toLowerCase() %>'<% } %>);
<%_ if (searchEngineAny) { _%>
protected resourceSearchUrl = this.applicationConfigService.getEndpointFor('api/<%= entityApiUrl %>/_search'<% if ((applicationTypeGateway || applicationTypeMicroservice) && locals.microserviceName) { %>, '<%= microserviceName.toLowerCase() %>'<% } %>);
<%_ } _%>

constructor(protected http: HttpClient, protected applicationConfigService: ApplicationConfigService) {}

<%_ if (!readOnly) { _%>
create(<%= entityInstance %>: New<%= entityAngularName %>): Observable<EntityResponseType> {
<%_ if (anyFieldIsDateDerived) { _%>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
.map(relationships => relationships.filter(rel => rel.persistableRelationship))
.filter(relationships => relationships.length > 0);
_%>
import { Component, OnInit<% if (anyFieldHasImageContentType) { %>, ElementRef<% } %> } from '@angular/core';
import { Component, inject, OnInit<% if (anyFieldHasImageContentType) { %>, ElementRef<% } %> } from '@angular/core';
import { HttpResponse } from '@angular/common/http';
import { ActivatedRoute } from '@angular/router';
import { Observable } from 'rxjs';
Expand Down Expand Up @@ -88,32 +88,33 @@ export class <%= entityAngularName %>UpdateComponent implements OnInit {
<%_ } _%>
<%_ } _%>

editForm: <%= entityAngularName %>FormGroup = this.<%= entityInstance %>FormService.create<%= entityAngularName %>FormGroup();

constructor(
<%_ if (anyFieldIsBlobDerived) { _%>
protected dataUtils: DataUtils,
protected eventManager: EventManager,
protected dataUtils = inject(DataUtils);
protected eventManager = inject(EventManager);
<%_ } _%>
protected <%= entityInstance %>Service: <%= entityAngularName %>Service,
protected <%= entityInstance %>FormService: <%= entityAngularName %>FormService,
protected <%= entityInstance %>Service = inject(<%= entityAngularName %>Service);
protected <%= entityInstance %>FormService = inject(<%= entityAngularName %>FormService);
<%_
Object.keys(differentRelationships).forEach(key => {
if (differentRelationships[key].some(rel => rel.persistableRelationship)) {
const uniqueRel = differentRelationships[key][0];
if (uniqueRel.otherEntityAngularName !== entityAngularName) {
_%>
protected <%= uniqueRel.otherEntityName %>Service: <%= uniqueRel.otherEntityAngularName %>Service,
protected <%= uniqueRel.otherEntityName %>Service = inject(<%= uniqueRel.otherEntityAngularName %>Service);
<%_
}
}
});
_%>
<%_ if (anyFieldHasImageContentType) { _%>
protected elementRef: ElementRef,
protected elementRef = inject(ElementRef);
<%_ } _%>
protected activatedRoute: ActivatedRoute,
) {}
protected activatedRoute = inject(ActivatedRoute);

// eslint-disable-next-line @typescript-eslint/member-ordering
editForm: <%= entityAngularName %>FormGroup = this.<%= entityInstance %>FormService.create<%= entityAngularName %>FormGroup();

constructor() {}
<%_ for (const relationshipsByEntity of Object.values(differentRelationships).filter(arr => arr.some(rel => rel.persistableRelationship && rel.otherEntity.primaryKey))) {
const { otherEntity } = relationshipsByEntity[0];
_%>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
See the License for the specific language governing permissions and
limitations under the License.
-%>
import { Component, OnDestroy } from '@angular/core';
import { Component, inject, OnDestroy } from '@angular/core';
import { HttpErrorResponse } from '@angular/common/http';
import { Subscription } from 'rxjs';
import { CommonModule } from '@angular/common';
Expand All @@ -40,13 +40,19 @@ export class AlertErrorComponent implements OnDestroy {
errorListener: Subscription;
httpErrorListener: Subscription;

constructor(private alertService: AlertService, private eventManager: EventManager<% if (enableTranslation) { %>, translateService: TranslateService<% } %>) {
this.errorListener = eventManager.subscribe('<%= frontendAppName %>.error', (response: EventWithContent<unknown> | string) => {
private alertService = inject(AlertService);
private eventManager = inject(EventManager);
<% if (enableTranslation) { %>
private translateService = inject(TranslateService);
<% } %>

constructor() {
this.errorListener = this.eventManager.subscribe('<%= frontendAppName %>.error', (response: EventWithContent<unknown> | string) => {
const errorResponse = (response as EventWithContent<AlertError>).content;
this.addErrorAlert(errorResponse.message<% if (enableTranslation) { %>, errorResponse.key, errorResponse.params<% } %>);
});

this.httpErrorListener = eventManager.subscribe('<%= frontendAppName %>.httpError', (response: EventWithContent<unknown> | string) => {
this.httpErrorListener = this.eventManager.subscribe('<%= frontendAppName %>.httpError', (response: EventWithContent<unknown> | string) => {
const httpErrorResponse = (response as EventWithContent<HttpErrorResponse>).content;
switch (httpErrorResponse.status) {
// connection refused, server not reachable
Expand All @@ -71,7 +77,7 @@ export class AlertErrorComponent implements OnDestroy {
}
if (errorHeader) {
<%_ if (enableTranslation) { _%>
const alertData = entityKey ? { entityName: translateService.instant(`global.menu.entities.${entityKey}`) } : undefined;
const alertData = entityKey ? { entityName: this.translateService.instant(`global.menu.entities.${entityKey}`) } : undefined;
<%_ } _%>
this.addErrorAlert(errorHeader<% if (enableTranslation) { %>, errorHeader, alertData<% } %>);
} else if (httpErrorResponse.error !== '' && httpErrorResponse.error.fieldErrors) {
Expand All @@ -84,7 +90,7 @@ export class AlertErrorComponent implements OnDestroy {
const convertedField: string = fieldError.field.replace(/\[\d*\]/g, '[]');
const fieldName: string =
<%_ if (enableTranslation) { _%>
translateService.instant(`<%= frontendAppName %>.${fieldError.objectName as string}.${convertedField}`);
this.translateService.instant(`<%= frontendAppName %>.${fieldError.objectName as string}.${convertedField}`);
<%_ } else { _%>
convertedField.charAt(0).toUpperCase() + convertedField.slice(1);
<%_ } _%>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
See the License for the specific language governing permissions and
limitations under the License.
-%>
import { NgModule } from '@angular/core';
import { inject, NgModule } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { TranslateModule, TranslateService, TranslateLoader, MissingTranslationHandler } from '@ngx-translate/core';
<%_ if (applicationTypeMicroservice) { _%>import { TranslateHttpLoader } from '@ngx-translate/http-loader';<%_ } _%>
Expand All @@ -42,12 +42,12 @@ function lazyTranslatePartialLoader(http: HttpClient): TranslateLoader {
],
})
export class LazyTranslationModule {
constructor(
private translateService: TranslateService,
private translateLoader: TranslateLoader,
stateStorageService: StateStorageService
) {
const currentLang = translateService.store.currentLang;
private translateService = inject(TranslateService);
private translateLoader = inject(TranslateLoader);
private stateStorageService = inject(StateStorageService);

constructor() {
const currentLang = this.translateService.store.currentLang;
this.translateLoader.getTranslation(currentLang).subscribe(translation => {
this.translateService.setTranslation(currentLang, translation);
});
Expand All @@ -71,10 +71,10 @@ export class LazyTranslationModule {
],
})
export class TranslationModule {
constructor(
private translateService: TranslateService,
private stateStorageService: StateStorageService
) {
private translateService = inject(TranslateService);
private stateStorageService = inject(StateStorageService);

constructor() {
this.translateService.setDefaultLang('<%= nativeLanguage %>');
// if user have changed language and navigates away from the application and back to the application then use previously choosed language
const langKey = this.stateStorageService.getLocale() ?? '<%= nativeLanguage %>';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
See the License for the specific language governing permissions and
limitations under the License.
-%>
import { Component, DebugElement } from '@angular/core';
import { Component, DebugElement, inject } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { FaIconComponent, FaIconLibrary } from '@fortawesome/angular-fontawesome';
Expand All @@ -42,9 +42,11 @@ class TestSortByDirectiveComponent {
sortAllowed = true;
transition = jest.fn();

constructor(library: FaIconLibrary) {
library.addIconPacks(fas);
library.addIcons(faSort, faSortDown, faSortUp);
private library = inject(FaIconLibrary);

constructor() {
this.library.addIconPacks(fas);
this.library.addIcons(faSort, faSortDown, faSortUp);
}
}

Expand Down

0 comments on commit 55e16f9

Please sign in to comment.