Make a service execute only once when a component is created

A service is created containing two integers to increment:

  • The first variable, outerCounter, needs to be incremented once and only once when the component is first rendered. Even if the component gets destroyed, then gets re-rendered, it shouldn’t increment.
  • The second variable, innerCounter, should start at 1 and then increment the component whenever needed.

In other words, outerCounter needs to be shared among all of the components and gets incremented once when a component is rendered once or n times, whereas innerCounter is not shared and is incremented independently of the complement.

For convenience, I have created a StackBlitz project. It has three different components and the required result is to have 1.1 for the first component, 2.1 for the second component and 3.1 for the last component. In case there inner counter is incremented in another tag, then it will be 1.2, 1.3, 1.4, etc in the first component, 2.2, 2.3, 2.4, etc. in the second component and 3.2, 3.3, 3.4, etc. in the last component. Any assistance would be appreciated!

3

We can use a service, that contains two objects outerCounterMap and innerCounterMap their job is to store the counter, based on the component name.

The only special condition is that, we can only increment the outer counter only once, when the value is set to zero.

 incrementOuterCounter(className: string): void {
    if (!this.outerCounterMap[className]) {
      this.outerCounterMap[className] = 0;
    }
    if (this.outerCounterMap[className] === 0) { // update only once!
      this.internalInnerCounter++;
      this.outerCounterMap[className] = this.internalInnerCounter;
    }
  }

Now, we can use this.constructor.name to get the component name, to track the indexes based on this name, as the key to the maps of the service(outerCounterMap and innerCounterMap). This will generate the desired output.

Full Code:

one.component.ts

import { AfterViewInit, Component, OnDestroy } from '@angular/core';
import { CounterService } from '../../services/counter.service';

@Component({
  selector: 'app-one',
  standalone: true,
  imports: [],
  templateUrl: './one.component.html',
  styleUrl: './one.component.css',
})
export class OneComponent {
  className: string = this.constructor.name;
  label: string = '';
  constructor(public counter: CounterService) {
    this.counter.incrementOuterCounter(this.className);
    this.counter.incrementInnerCounter(this.className);
  }

  getLabel() {
    return (
      this.counter.getOuterCounter(this.className) +
      '.' +
      this.counter.getInnerCounter(this.className)
    );
  }
}

service.ts

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root',
})
export class CounterService {
  private outerCounterMap: { [key: string]: number } = {};
  private innerCounterMap: { [key: string]: number } = {};
  internalInnerCounter = 0;
  constructor() {}

  getInnerCounter(className: string): number {
    return this.innerCounterMap[className] || 0;
  }

  incrementInnerCounter(className: string): void {
    if (!this.innerCounterMap[className]) {
      this.innerCounterMap[className] = 0;
    }
    this.innerCounterMap[className] = this.innerCounterMap[className] + 1;
  }

  getOuterCounter(className: string): number {
    return this.outerCounterMap[className] || 0;
  }
  incrementOuterCounter(className: string): void {
    if (!this.outerCounterMap[className]) {
      this.outerCounterMap[className] = 0;
    }
    if (this.outerCounterMap[className] === 0) {
      this.internalInnerCounter++;
      this.outerCounterMap[className] = this.internalInnerCounter;
    }
  }
}

Stackblitz Demo

2

A solution using 2 service instances:

@Injectable({
    providedIn: "root"
})
export class Counter {

    private _counter = 0;

    increment() {
       this._counter++;
    }

    get counter(): number {
       return this._counter;
    }
}

The component using the counters:


import { Counter } from './counter';
...

@Component({
    templateUrl: '....',
    standalone: true,
    imports[ ... ],
    providers: [
       Counter
    }
})
export class MyComponent {
    innerCounter = inject(Counter); // the instance provided by this component
    outerCounter = inject(Counter, { skipSelf: true }); // the instance provided in root

    ....
}

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật