대체 주입 신택스(syntax), implements, 서비스를 주입하는 다른 방식, 인젝터

Goofi·2023년 12월 17일
0

대체 주입 신택스(syntax)

생성자 함수를 통해 서비스(또는 일반적으로 의존성)를 컴포넌트에 주입하는 것이 이러한 주입을 수행하는 가장 일반적인 방법입니다. 여러분이 작업하게 될 대부분의 Angular 프로젝트에서 이 접근 방식을 보게 될 것입니다.

그러나 종속성을 주입하는 다른 방법도 있습니다: 바로 Angular의 inject() 함수를 사용하는 것입니다.

다음과 같이 LoggingService를 주입하는 대신:
@Component(...)
export class AccountComponent {
// @Input() & @Output() code as shown in the previous lecture

constructor(private loggingService: LoggingService) {}
}
inject() 함수를 사용하여 다음과 같이 주입할 수 있습니다:
import { Component, Input, Output, inject } from '@angular/core'; // <- Add inject import

@Component(...)
export class AccountComponent {
// @Input() & @Output() code as shown in the previous lecture
private loggingService?: LoggingService; // <- must be added

constructor() {
this.loggingService = inject(LoggingService);
}
}
어떤 접근 방식을 선호하느냐는 전적으로 여러분에게 달려 있습니다. 이 강좌에서는(그리고 대부분의 프로젝트에서 언급했듯이) 생성자 접근 방식을 사용합니다.

implements

implements 키워드는 TypeScript에서 인터페이스(interface)를 구현할 때 사용됩니다. 인터페이스는 특정 메서드나 속성이 클래스에서 구현되도록 강제하는 역할을 합니다. 따라서 implements를 사용하면 해당 클래스가 특정 인터페이스의 구현체임을 명시적으로 나타낼 수 있습니다.

예를 들어, 위의 코드에서 AppComponent 클래스가 OnInit 인터페이스를 구현하고 있습니다. 이는 Angular 라이프사이클 훅 중 하나인 ngOnInit 메서드를 반드시 구현해야 함을 의미합니다. ngOnInit 메서드는 컴포넌트가 초기화될 때 호출되는 메서드로, 주로 초기 데이터 로딩이나 초기화 로직을 수행하는 데 사용됩니다.

따라서 implements OnInit를 사용함으로써 Angular는 해당 클래스가 OnInit 인터페이스를 준수하여 ngOnInit 메서드를 반드시 구현해야 한다는 것을 인지하게 됩니다. 만약 이 메서드를 구현하지 않으면 TypeScript 컴파일러가 오류를 발생시킬 것입니다.

종합하면, implements 키워드를 사용하여 인터페이스를 구현함으로써 클래스가 특정 규약을 따르도록 보장하고, 개발자에게 필수적으로 구현해야 하는 메서드나 속성이 있는지 확인할 수 있습니다.

서비스를 주입하는 다른 방식

Angular 6 이상을 사용하는 경우(체크하려면 package.json 으로) 다른 방식으로 애플리케이션 전체에 서비스를 제공할 수 있습니다.
AppModule의 providers[] 배열에 서비스 클래스를 추가하는 대신, @Injectable() 에서 다음 구성을 설정할 수 있습니다:
@Injectable({providedIn: 'root'})
export class MyService { ... }
이것은 다음과 정확히 동일합니다:
export class MyService { ... }
그리고
import { MyService } from './path/to/my.service';

@NgModule({
...
providers: [MyService]
})
export class AppModule { ... }
이 새로운 구문을 사용하는 것은 완전히 선택 사항이며, 기존구문 (providers[]사용)은 여전히 작동합니다.
하지만 '새 구문'은 한 가지 이점을 제공합니다.
Angular에서 서비스를 지연 로드할 수 있고(배후에서),
중복 코드를 자동으로 제거할 수 있습니다.
이렇게하면성능과로드속도가향상될수있지만, 일반적으로 더 큰서비스 및 앱에만 적용됩니다.

인젝터

import { Component, EventEmitter, Input, Output } from '@angular/core';
import {LoggingService} from "../logging.service";
import {AccountService} from "../account.service";

@Component({
  selector: 'app-account',
  templateUrl: './account.component.html',
  styleUrls: ['./account.component.css'],
  providers : [LoggingService, AccountService]
})
export class AccountComponent {
  @Input() account: {name: string, status: string};
  @Input() id: number;

  constructor(private loggingService : LoggingService,
              private accountService : AccountService) {}

  onSetTo(status: string) {
    this.accountService.updateStatus(this.id, status);
    this.loggingService.logStatusChange(status);
  }
}
import {Component, OnInit} from '@angular/core';
import {AccountService} from "./account.service";

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers : [AccountService]
})
export class AppComponent implements OnInit{
  accounts : { name : string, status : string }[] = [];

  constructor(private accountsService : AccountService) {}

  ngOnInit() {
    // console.log(this.accountsService.accounts)
    this.accounts = this.accountsService.accounts;
  }
}

Q)AppComponent와 AppAccount는 서로 다른 의존성이 주입되는거지?

A-ChatGPT)

네, 맞습니다. AppComponent와 AccountComponent는 서로 다른 의존성이 주입되고 있습니다. 이는 Angular의 의존성 주입(Dependency Injection) 시스템을 통해 이루어집니다.

각 컴포넌트는 providers 배열을 사용하여 의존성을 설정하고 있습니다. 각 컴포넌트 내에서 providers 배열에 등록된 서비스는 해당 컴포넌트의 인스턴스에서만 사용 가능한 범위를 가집니다. 이것은 의존성 주입의 특징 중 하나로, 서로 다른 컴포넌트 간에 독립적인 서비스 인스턴스를 가질 수 있습니다.

AppComponent에서는 AccountService를 제공자로 설정하고 있습니다. 이는 AppComponent 및 해당 하위 컴포넌트들이 같은 인스턴스의 AccountService를 공유하게 됩니다.

AccountComponent에서는 LoggingService와 AccountService를 제공자로 설정하고 있습니다. 따라서 AccountComponent 및 해당 하위 컴포넌트들은 같은 인스턴스의 LoggingService와 AccountService를 공유하게 됩니다.

즉, 각 컴포넌트는 자체적인 의존성 주입을 가지며, 서로 간에는 독립적인 의존성을 유지하고 있습니다.

Q) 그럼 AccountComponent에서 서비스에 있는 값에 있는 배열에 새로운 값을 추가하면 AppComponent에서는 별개이기 때문에 기존 배열을 출력하는거야?

A-ChatGPT)
네, 맞습니다. Angular의 의존성 주입은 기본적으로 각 컴포넌트마다 독립적인 인스턴스를 생성하므로, AccountComponent에서 서비스에 있는 배열에 새로운 값을 추가하면 AppComponent에서는 별개의 인스턴스를 유지하고 있어 기존 배열을 출력하는 것과 독립적입니다.

다시 말해, AppComponent와 AccountComponent는 서로 다른 인스턴스를 가지는 서비스를 주입받아 사용하고 있으므로, 하나의 컴포넌트에서 서비스의 상태를 변경하더라도 다른 컴포넌트에는 영향을 미치지 않습니다. 이는 Angular의 컴포넌트 간의 독립성을 유지하면서 각각의 상태를 관리할 수 있도록 하는 중요한 특성 중 하나입니다.

profile
오늘보단 내일이 강한 개발자입니다!!🧑🏻‍💻

0개의 댓글