@Component({
selector: 'zippy',
template: `
Toggle
`})
export class ZippyComponent {
visible = true;
@Output() open = new EventEmitter();
@Output() close = new EventEmitter();
toggle() {
this.visible = !this.visible;
if (this.visible) {
this.open.emit(null);
} else {
this.close.emit(null);
}
}
}
===== HTTP =====
Angular의 HttpClient는 HTTP 메서드 호출에서 관찰 가능 항목을 반환합니다. 예를 들어 http.get('/api')는 관찰 가능을 반환합니다. 이는 약속 기반 HTTP API에 비해 몇 가지 장점을 제공합니다.
* Observables는 서버 응답을 변경하지 않습니다 (약속에 대한 .then() 호출을 통해 발생할 수 있음). 대신 일련의 연산자를 사용하여 필요에 따라 값을 변환 할 수 있습니다.
* HTTP 요청은 unsubscribe() 메소드를 통해 취소 할 수 있습니다.
* 진행 상황 이벤트 업데이트를 가져 오기 위해 요청을 구성 할 수 있습니다.
* 실패한 요청은 쉽게 재 시도 될 수 있습니다.
===== Async pipe =====
AsyncPipe는 관찰 가능 또는 약속을 구독하고 방출 한 최신 값을 반환합니다. 새 값이 방출되면 파이프는 변경 사항을 검사 할 구성 요소를 표시합니다.
다음 예제에서는 관찰 할 수있는 시간을 구성 요소의 뷰에 바인딩합니다. 관측 가능 항목은 현재 시간으로 뷰를 계속 업데이트합니다.
@Component({
selector: 'async-observable-pipe',
template: `observable|async< /code>:
Time: {{ time | async }}`
})
export class AsyncObservablePipeComponent {
time = new Observable(observer =>
setInterval(() => observer.next(new Date().toString()), 1000)
);
}
===== Router =====
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;
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;
}
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));
}
}
===== Reactive forms =====
반응 형 폼은 관찰 값을 사용하여 폼 컨트롤 값을 모니터링하는 속성을 가지고 있습니다. 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)
);
}
}