programing

Angular 6에서 서비스를 생성 할 때 Injectable 데코레이터와 함께 제공되는 목적은 무엇입니까?

nasanasas 2020. 11. 12. 08:21
반응형

Angular 6에서 서비스를 생성 할 때 Injectable 데코레이터와 함께 제공되는 목적은 무엇입니까?


Angular CLI에서 서비스를 생성 할 때 Injectable 데코레이터에 대한 기본값이 'root'인 'provided in'속성이있는 추가 메타 데이터를 추가합니다.

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

providedIn은 정확히 무엇을합니까? 이것이 전체 응용 프로그램에 대해 '글로벌'유형의 싱글 톤 서비스처럼 서비스를 제공한다고 가정하고 있지만 AppModule의 공급자 배열에서 이러한 서비스를 선언하는 것이 더 깔끔하지 않을까요?

최신 정보:

다른 사람을 위해 다음 단락은 특히 기능 모듈에만 서비스를 제공하려는 경우 또 다른 좋은 설명을 제공했습니다.

이제 @Injectable()providedIn속성을 사용하여 데코레이터 내부에서 직접 공급자를 등록하는 새롭고 권장되는 방법이 있습니다. 'root'응용 프로그램의 값 또는 모듈로 허용 합니다. 당신이 사용하는 경우 'root', 당신은 injectable응용 프로그램에서 싱글로 등록됩니다, 당신은 루트 모듈의 공급 업체에 추가 할 필요가 없습니다. 마찬가지로을 사용 providedIn: UsersModule하면 injectable모듈에 UsersModule추가하지 않고 의 공급자로 등록됩니다 providers. " -https : //blog.ninja-squad.com/2018/05/04/what-is-new-angular -6 /

업데이트 2 :

추가 조사 결과, 나는 providedIn: 'root'

provide루트 모듈이 아닌 다른 모듈의 서비스 를 원하면 providers기능 모듈의 데코레이터에서 배열을 사용하는 것이 좋습니다 . 그렇지 않으면 순환 종속성에 시달립니다. 여기에서 흥미로운 토론-https: //github.com/angular/angular-cli/issues/10170


providedIn을 사용하면 인젝터 블이 모듈의 제공자에 추가되지 않고 모듈의 제공자로 등록됩니다.

에서 Docs

서비스 자체는 CLI가 생성 한 클래스이며 @Injectable로 장식되어 있습니다. 기본적으로이 데코레이터는 서비스 공급자를 생성하는 providedIn 속성으로 구성됩니다. 이 경우, providedIn : 'root'는 서비스가 루트 인젝터에서 제공되어야 함을 지정합니다.


providedIn: 'root' Angular 6 이후 서비스를 제공하는 가장 쉽고 효율적인 방법입니다.

  1. 이 서비스는 모듈의 공급자 배열 (예 : Angular <= 5)에 추가 할 필요없이 단일 항목으로 응용 프로그램 전체에서 사용할 수 있습니다.
  2. 서비스가 지연로드 된 모듈 내에서만 사용되는 경우 해당 모듈과 함께 지연로드됩니다.
  3. 사용하지 않으면 빌드에 포함되지 않습니다 (나무 흔들림).

자세한 내용은 문서NgModule FAQ를 읽어보십시오.

Btw :

  1. 응용 프로그램 전체의 싱글 톤을 원하지 않는 경우 대신 공급자의 구성 요소 배열을 사용하십시오.
  2. 다른 개발자가 특정 모듈 외부에서 귀하의 서비스를 사용하지 않도록 범위를 제한하려면 대신 공급자의 NgModule 배열을 사용하십시오.

providedIn은 Angular에게 루트 인젝터가 서비스의 인스턴스를 생성한다는 것을 알려줍니다. 이러한 방식으로 제공되는 서비스는 전체 애플리케이션에서 자동으로 사용할 수 있으며 모듈에 나열 할 필요가 없습니다.

서비스 클래스는 자체 공급자 역할을 할 수 있으므로 @Injectable 데코레이터에서 정의하는 것이 필요한 모든 등록 인 이유입니다.


문서에서

Injectable Decorator는 무엇입니까?

Injector에서 생성 할 수 있도록 클래스를 표시합니다.

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

@Injectable({
  providedIn: 'root',
})
export class UserService {
}

서비스 자체는 CLI가 생성 한 클래스이며 @Injectable ()로 장식되어 있습니다.

providedIn은 정확히 무엇을합니까?

Determines which injectors will provide the injectable, by either associating it with an @NgModule or other InjectorType, or by specifying that this injectable should be provided in the 'root' injector, which will be the application-level injector in most apps.

providedIn: Type<any> | 'root' | null

providedIn: 'root'

When you provide the service at the root level, Angular creates a single, shared instance of service and injects it into any class that asks for it. Registering the provider in the @Injectable() metadata also allows Angular to optimize an app by removing the service from the compiled app if it isn't used.

providedIn: Module

It's also possible to specify that a service should be provided in a particular @NgModule. For example, if you don't want a service to be available to applications unless they import a module you've created, you can specify that the service should be provided in the module

import { Injectable } from '@angular/core';
import { UserModule } from './user.module';

@Injectable({
  providedIn: UserModule,
})
export class UserService {
}

This method is preferred because it enables Tree-shaking (Tree shaking is a step in a build process that removes unused code from a code base) of the service if nothing injects it.

If it's not possible to specify in the service which module should provide it, you can also declare a provider for the service within the module:

import { NgModule } from '@angular/core';
import { UserService } from './user.service';

@NgModule({
  providers: [UserService],
})
export class UserModule {
}

According to the Documentation:

Registering the provider in the @Injectable() metadata also allows Angular to optimize an app by removing the service from the compiled app if it isn't used.

참고URL : https://stackoverflow.com/questions/50848357/what-is-the-purpose-of-providedin-with-the-injectable-decorator-when-generating

반응형