Angular Subscribe() 메서드

Rana Hasnain Khan 2024년2월15일
Angular Subscribe() 메서드

Angular의 subscribe() 메소드를 소개하고 우리 애플리케이션에서 사용할 것입니다.

Angular Subscribe

Subscribe()는 Angular에서 observer를 observer와 observable 이벤트를 연결하는 메서드이다. 이러한 관찰 가능 항목이 변경될 때마다 코드가 실행되고 subscribe 메서드를 사용하여 결과 또는 변경 사항을 관찰합니다. Subscribe()는 Angular에서 내부적으로 사용하는 rxjs 라이브러리의 메소드입니다.

뉴스레터는 현재 웹사이트의 가장 일반적인 부분입니다. 그것들을 관찰 가능한 사건으로 상상하고 우리는 관찰자라고 상상해 봅시다. 웹사이트의 뉴스레터 양식에 이메일을 입력하면 관찰 가능한 이벤트를 구독합니다. 해당 웹사이트에서 새로운 뉴스레터가 출시될 때마다 해당 이벤트를 구독 취소할 때까지 이메일로 뉴스레터를 수신합니다.

마찬가지로 Angular 애플리케이션에서 관찰하려는 함수가 있으면 해당 함수를 구독합니다. 해당 함수가 변경될 때마다 subscribe() 메서드를 사용하여 변경 사항을 볼 수 있습니다.

Subscribe()next, error, complete의 세 가지 메소드를 매개변수로 사용합니다.

  1. next 메소드를 사용하여 observable이 내보낸 모든 값을 전달할 수 있습니다.
  2. error 메서드를 사용하여 스트림의 어딘가에서 발생하는 모든 오류를 전달할 수 있습니다.
  3. complete 방법을 사용하여 전체 관찰 가능한 이벤트가 완료되면 값을 전달할 수 있습니다.

subscribe()를 자세히 이해하기 위해 예를 들어 보겠습니다. 먼저 next 메소드를 사용하여 관찰자에게 값을 전달하는 assignValue() 함수를 생성하는 subscribe.service.ts라는 새 서비스 파일을 생성합니다.

subsribe.service.ts의 코드는 다음과 같습니다.

# angular
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root',
})
export class SubscribeService {
  assignValue() {
    const SubscribeObservable = new Observable((observer) => {
      observer.next('Angular');
    });
    return SubscribeObservable;
  }
}

다음으로 app.module.ts에서 이 서비스를 가져오고 @NgModule 내부에서 공급자로 정의합니다.

# angular
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';

import { AppComponent } from './app.component';
import { HelloComponent } from './hello.component';
import { SubscribeService } from './subscribe.service';

@NgModule({
  imports: [BrowserModule, FormsModule],
  declarations: [AppComponent, HelloComponent],
  bootstrap: [AppComponent],
  providers: [SubscribeService],
})
export class AppModule {}

app.component.ts 파일 내부의 다음 단계에서 서비스의 생성자와 관찰자로부터 값을 가져올 함수를 생성합니다. app.component.ts 파일에서 서비스를 가져오는 것을 잊지 마십시오.

# angular
import { Component, VERSION } from '@angular/core';
import { SubscribeService } from './subscribe.service';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  name = 'Angular ' + VERSION.major;

  constructor(private SubscribeService: SubscribeService) {}

  ngClick() {
    this.SubscribeService.assignValue().subscribe((result) => {
      console.log(result);
    });
  }
}

이제 app.component.html에 템플릿을 만듭니다.

# angular
<hello name="{{ name }}"></hello>
<button (click)="ngClick()">Click Here to see result</button>

출력:

Angular 구독 예

Rana Hasnain Khan avatar Rana Hasnain Khan avatar

Rana is a computer science graduate passionate about helping people to build and diagnose scalable web application problems and problems developers face across the full-stack.

LinkedIn