문서의 이전 판입니다!
Angular는 다양한 공통 비동기 작업을 처리 할 수있는 인터페이스로 observables를 사용합니다. 예 :
Angular는 @Output() 데코레이터를 통해 구성 요소의 값을 게시 할 때 사용되는 EventEmitter 클래스를 제공합니다. EventEmitter는 Observable을 확장하고 emit() 메서드를 추가하여 임의의 값을 보낼 수 있도록합니다. emit()을 호출하면 방출 된 값을 가입 된 관찰자의 next() 메서드로 전달합니다.
사용법의 좋은 예는 EventEmitter 문서에서 찾을 수 있습니다. 다음은 열기 및 닫기 이벤트를 수신하는 예제 구성 요소입니다.
<zippy (open)=“onOpen($event)” (close)=“onClose($event)”> </zippy>
구성 요소 정의는 다음과 같습니다.
@Component({ selector: 'zippy', template: ` <div class="zippy"> <div (click)="toggle()">Toggle</div> <div [hidden]="!visible"> <ng-content></ng-content> </div> </div>`}) export class ZippyComponent { visible = true; @Output() open = new EventEmitter<any>(); @Output() close = new EventEmitter<any>(); toggle() { this.visible = !this.visible; if (this.visible) { this.open.emit(null); } else { this.close.emit(null); } } }
Angular의 HttpClient는 HTTP 메서드 호출에서 관찰 가능 항목을 반환합니다. 예를 들어 http.get ( '/ api')는 관찰 가능을 반환합니다. 이는 약속 기반 HTTP API에 비해 몇 가지 장점을 제공합니다.
Observables는 서버 응답을 변경하지 않습니다 (약속에 대한 .then () 호출을 통해 발생할 수 있음). 대신 일련의 연산자를 사용하여 필요에 따라 값을 변환 할 수 있습니다. HTTP 요청은 unsubscribe () 메소드를 통해 취소 할 수 있습니다. 진행 상황 이벤트 업데이트를 가져 오기 위해 요청을 구성 할 수 있습니다. 실패한 요청은 쉽게 재 시도 될 수 있습니다.
AsyncPipe는 관찰 가능 또는 약속을 구독하고 방출 한 최신 값을 반환합니다. 새 값이 방출되면 파이프는 변경 사항을 검사 할 구성 요소를 표시합니다.
다음 예제에서는 관찰 할 수있는 시간을 구성 요소의 뷰에 바인딩합니다. 관측 가능 항목은 현재 시간으로 뷰를 계속 업데이트합니다.
@Component({ selector: 'async-observable-pipe', template: `<div><code>observable|async
:
Time: {{ time | async }}</div>`
}) export class AsyncObservablePipeComponent {
time = new Observable(observer => setInterval(() => observer.next(new Date().toString()), 1000) );
} </code>
Router.events는 이벤트를 관찰 가능 객체로 제공합니다. RxJS의 filter () 연산자를 사용하여 관심있는 이벤트를 찾고 탐색 프로세스의 이벤트 순서를 기반으로 의사 결정을 내리기 위해 구독 할 수 있습니다. 다음은 그 예입니다.
import { Router, NavigationStart } from '@angular/router'; import { filter } from 'rxjs/operators'; @Component({ selector: 'app-routable', templateUrl: './routable.component.html', styleUrls: ['./routable.component.css'] }) export class Routable1Component implements OnInit { navStart: Observable<NavigationStart>; constructor(private router: Router) { // Create a new Observable that publishes only the NavigationStart event this.navStart = router.events.pipe( filter(evt => evt instanceof NavigationStart) ) as Observable<NavigationStart>; } ngOnInit() { this.navStart.subscribe(evt => console.log('Navigation Started!')); } }
ActivatedRoute는 관찰 경로를 사용하여 경로 경로 및 매개 변수에 대한 정보를 가져 오는 주입 라우터 서비스입니다. 예를 들어, ActivateRoute.url에는 경로 경로를보고하는 관찰 가능 항목이 있습니다. 다음은 그 예입니다.
import { ActivatedRoute } from '@angular/router'; @Component({ selector: 'app-routable', templateUrl: './routable.component.html', styleUrls: ['./routable.component.css'] }) export class Routable2Component implements OnInit { constructor(private activatedRoute: ActivatedRoute) {} ngOnInit() { this.activatedRoute.url .subscribe(url => console.log('The URL changed to: ' + url)); } }
반응 형 폼은 관찰 값을 사용하여 폼 컨트롤 값을 모니터링하는 속성을 가지고 있습니다. FormControl 속성 valueChanges 및 statusChanges에는 변경 이벤트를 발생시키는 관찰 가능 항목이 포함되어 있습니다. 관찰 가능한 폼 - 컨트롤 속성을 구독하는 것은 컴포넌트 클래스 내에서 어플리케이션 로직을 트리거하는 방법입니다. 예 :
import { FormGroup } from '@angular/forms'; @Component({ selector: 'my-component', template: 'MyComponent Template' }) export class MyComponent implements OnInit { nameChangeLog: string[] = []; heroForm: FormGroup; ngOnInit() { this.logNameChange(); } logNameChange() { const nameControl = this.heroForm.get('name'); nameControl.valueChanges.forEach( (value: string) => this.nameChangeLog.push(value) ); } }