나는 실질적인 예에서 관찰 가능한 것을 이해하고 싶다. APP가 실행중인 상태 인 한 1 분마다 API 호출을하고 싶다고 가정합니다. 현재 setInterval
다음과 같은 기능을 사용하여 수행하고 있습니다.
ngOnInit() {
setInterval(val => this.getDataFromAPI(), 60000)
}
getDataFromAPI() {
this.dataServices.getDataFromAPI().subscribe((data: any) => {
this.gaugeData = data;
},
error =>{
console.log('error')
});
}
에서 dataServices
파일 방법 'getDataFromAPI이 which is responsible of making the
HTTP`가 호출합니다.
getDataFromAPI
return this.http.get(this.base_url + this.endPoint, {
headers: {
'tokenid': this.tokenId,
'accountid': this.accountId'
}, params: { groupId: groupId, date: '2020-10-05T11:30:00-07:00' }
})
.toPromise().then(res => {
return res;
});
}
위의 예는 매우 잘 작동하지만이 기사에서 RxJS Observable 이해 및 왜 필요한지 언급했듯이 . 구독과 함께 Observable을 만들고 사용하는 다른 방법이 있습니다. 내가 제공 한 예제에서 옵저버 블을 어떻게 만들고 사용합니까?
timer
와 함께 사용할 수 있습니다 mergeMap
.
이미 다음과 같은 관찰 가능 항목이 있습니다.
const apiCall = this.dataServices.getDataFromAPI()
다른 옵저버 블을 생성해야합니다. 이것은 1 초 후에 옵저버 블을 시작하고 1 초마다 방출합니다.
const myTimer = timer(1000, 1000)
구성 요소에 빈 구독을 생성하면 나중에 구독을 취소 할 수 있습니다.
sub: Subscription
이제 다음에서 구독 할 수 있습니다 ngOnInit()
.
ngOnInit() {
const apiCall = this.dataServices.getDataFromAPI()
const myTimer = timer(1000, 1000)
this.sub = myTimer
.pipe(
mergeMap( () => this.dataServices.getDataFromAPI() )
)
.subscribe( data => this.gaugeData = data )
}
완료되면 구독을 취소하는 것을 잊지 마십시오. 그렇지 않으면 메모리 누수가 발생합니다.
ngOnDestroy() {
this.sub.unsubscribe()
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다