Dusan
Dusan

Reputation: 53

Shared component constructor logging service 5 times

I have a CommunicationService which i want to use throughout my application. When i instantiate it in a constructor and then logging it i noticed that it gets logged five times, why is this happening considering that in my communication service i've set:

  @Injectable({
    providedIn: 'root',
})

And i am not providing it anywhere else, also it's not in the providers under AppModule which is my main and only module.

This is my communication service:

import {Injectable} from '@angular/core';
import {Subject, BehaviorSubject} from 'rxjs';

@Injectable({
    providedIn: 'root',
})
export class CommunicationService {
    private sendLabel = new Subject<string>();
    labelConfirmed = this.sendLabel.asObservable();

    announceLabel(label: string){
        this.sendLabel.next(label);
    }

}

And this is how i'm using it:

import {Component, Input, OnInit} from '@angular/core';
import {CommunicationService} from "../../services/communication-service";

@Component({
    selector: 'app-column-filter',
    templateUrl: './column-filter.component.html',
    styleUrls: ['./column-filter.component.css'],
})
export class ColumnFilterComponent implements OnInit {
    @Input() selectedLabel: any;


    constructor(private cs: CommunicationService) {
        console.log(this.cs);
    }

    ngOnInit() {
        this.cs.labelConfirmed
            .subscribe((r)=>{
            this.selectedLabel = r;
        })
    }

}

Also here's my AppModule:

import {NgModule} from '@angular/core';
import {FormsModule, ReactiveFormsModule} from '@angular/forms';
import {HttpClientModule, HTTP_INTERCEPTORS} from '@angular/common/http';
import {BrowserModule} from '@angular/platform-browser';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {AppRoutes} from './app.routes';
import {BreadcrumbModule} from 'primeng/breadcrumb';


import {AppComponent} from './app.component';
import {AppMainComponent} from './app.main.component';
import {AppMenuComponent, AppSubMenuComponent} from './app.menu.component';
import {AppTopbarComponent} from './app.topbar.component';
import {AppFooterComponent} from './app.footer.component';
import {AppBreadcrumbComponent} from './app.breadcrumb.component';
import {CanDeactivateGuard} from './services/can-deactivate-guard.service';
import {CommunicationService} from './services/communication-service';
import {AppNotfoundComponent} from './pages/app.notfound.component';
import {AppErrorComponent} from './pages/app.error.component';
import {AppAccessdeniedComponent} from './pages/app.accessdenied.component';
import {DashboardComponent} from './view/dashboard.component';
import {BreadcrumbService} from './services/breadcrumb.service';

import { ColumnFilterComponent } from './pages/column-filter/column-filter.component';

@NgModule({
    imports: [
        BrowserModule,
        FormsModule,
        ReactiveFormsModule,
        AppRoutes,
        HttpClientModule,
        BrowserAnimationsModule,

    ],
    exports: [
        FormsModule,
        ReactiveFormsModule,
    ],
    declarations: [
        AppComponent,
        AppMainComponent,
        AppMenuComponent,
        AppSubMenuComponent,
        AppTopbarComponent,
        AppFooterComponent,
        AppBreadcrumbComponent,
        DashboardComponent,
        AppNotfoundComponent,
        AppErrorComponent,
        AppAccessdeniedComponent,
        AppLoginComponent,
        ColumnFilterComponent
    ],
    providers: [
        CanDeactivateGuard,
        BreadcrumbService,
    ],

    bootstrap: [AppComponent]
})
export class AppModule {
}

This is where i am using the component:

<div class="p-grid">
    <div class="p-col-12">
        <div class="card card-w-title">
            <div>
                <h1> {{objectTitle}}</h1>
                <button pButton type="button" (click)="showDialog()" label=" {{label}}"></button>
            </div>
            <p-table #dt [columns]="objectCols" (onHeaderCheckboxToggle)="selectAllObjects($event)" [value]="extractJobObjects" dataKey="id" (onRowSelect)="selectObject($event)" (onRowUnselect)="removeObject($event)" [paginator]="extractJobObjects?.length > 10" [rows]="10">
                <ng-template pTemplate="header" let-columns>
                    <tr>
                        <th *ngIf="rowExpandable && 
                           dt._totalRecords > 0"></th>
                        <th *ngFor="let col of columns" [pSortableColumn]="col.field">
                            {{col.header}}
                            <p-sortIcon [field]="col.field">
                            </p-sortIcon>
                        </th>
                        <th *ngIf="checkAll && 
                            dt._totalRecords > 0">
                            <p-tableHeaderCheckbox></p-tableHeaderCheckbox>
                        </th>
                    </tr>
                    <tr>
                        <th *ngIf="rowExpandable && 
                          dt._totalRecords > 0"></th>
                        <th *ngFor="let col of columns">
                            <app-column-filter [dt]="dt" [rowData]="col" [transformDropdown]="transformedDropdown" [selectedLabel]="selectedLabel" (emitDropdown)="filterFn($event)">
                            </app-column-filter>
                        </th>
                        <th *ngIf="checkAll && 
                          dt._totalRecords > 0">
                        </th>
                    </tr>
                </ng-template>
                <ng-template pTemplate="body" let-rowData let-ri="rowIndex" let-columns="columns" let-expanded="expanded">
                    <tr [pSelectableRow]="!rowData.transformed" [pSelectableRowDisabled]="rowData.transformed" [pSelectableRowIndex]="ri">
                        <td *ngIf="rowExpandable">
                            <a href="#" [pRowToggler]="rowData">
                                <i [ngClass]="expanded ? 'pi pi-chevron-down' : 'pi pi-chevron-right'"></i>
                            </a>
                        </td>
                        <td>
                            {{rowData.name}}
                        </td>
                        <td>
                            {{rowData.type}}
                        </td>
                        <td>
                            {{rowData.object_state_localization}}
                        </td>
                        <td>
                            {{rowData.object_status_localization}}
                        </td>
                        <td>
                            <div [ngClass]="{'red' : rowData.transformed, 'green' : !rowData.transformed}">
                            </div>
                        </td>
                        <td *ngIf="checkAll">
                            <p-tableCheckbox *ngIf="!rowData.transformed && rowData.object_state != 'DEPRECATED'" ngDefaultControl [value]="rowData" [index]="ri">
                            </p-tableCheckbox>
                        </td>
                    </tr>
                </ng-template>
                <ng-template pTemplate="rowexpansion" let-rowData let-columns="columns">
                    <tr>
                        <td [attr.colspan]="columns.length + 2">
                            <div class="p-grid">
                                <div class="p-col-2">
                                    <h1>{{localizationDataSource.get('com.fuentis.etl.transform.attributes')}}</h1>
                                </div>
                            </div>
                            <div class="p-grid" *ngFor="let item of rowData.attributes">
                                <span class="p-col">
                                    <b>{{item.key}}</b>:
                                    <span>{{item.value}}</span>
                                </span>
                            </div>
                        </td>
                    </tr>
                </ng-template>
            </p-table>
        </div>
    </div>
</div>

Is this normal behaviour for it to be logged 5 times in this case? I still don't understand why 5 times and not 2 or 3.

Upvotes: 0

Views: 86

Answers (1)

Amardeep Singh
Amardeep Singh

Reputation: 413

It 's your columnFilterComponent which is instantiating 5 times, And I am guessing that you are using this columnFilterComponent in 5 other components and that's why it is creating its instances 5 times and consoling the service 5 times

Upvotes: 0

Related Questions