2017-10-23 9 views
0

나는 firebase에서 한 번만 데이터를 가져 오려고합니다. 이 코드를 사용하여 실시간으로 변경 사항 및 업데이트를 구독하고 감시합니다.AngularFire 2 v5 데이터를 한 번만 가져 오는 방법?

this.profileData = this.fire.authState.switchMap(auth => this.db.object(`profile/${auth.uid}`).snapshotChanges().map(action => { 
     const $key = action.payload.key; 
     const data = { $key, ...action.payload.val() }; 
     return data; 

    })).subscribe(profile => { 

     this.profileData = profile; 


     console.log(this.profileData.username); // this is working. 

    }); 

나는 이런 식으로 뭔가를 시도했지만, 당신은 당신이 구독 취소에 대해 걱정해야 자신의 관찰 가능한을 사용하는 경우는이

this.profileData = this.fire.authState.switchMap(auth => this.db.object(`profile/${auth.uid}`)).take(1).subscribe(profile =>{ 

console.log(profile.username); 

})); 
+0

'take (1)'이 작동해야합니다. [구독하지 않고 한 번만 값을 얻으십시오.] (https://github.com/angular/angularfire2/issues/456 # issuecomment-241509299). – Grimthorr

+0

this.profileData = this.fire.authState.switchMap (auth => this.db.object ('profile/$ {auth.uid}')). console.log (this.profileData.username); 이 정의되지 않은 반환합니까? –

+0

with console.log (this.profileData) 이걸 가지고 있습니다 : http://prntscr.com/h0waiy –

답변

0

작동하지 않습니다.

각 구성 요소에는 ngOnInit, ngOnChange 등과 같은 많은 라이프 사이클 후크가 있습니다. 또한 ngOnDestroy 함수가 있으며 좋은 관행은 해당 후크에서 관찰 가능 항목을 등록 취소하는 것입니다.

데이터를 한 번만 가져오고 싶다면 구독을 취소 한 곳에서 기능을 호출하는 것이 가장 좋습니다. 여기에 대한 자세한 정보가있는 링크가 있습니다 : Angular/RxJs When should I unsubscribe from `Subscription`

+0

Logged Thankss.what 내가 게시 한 두 번째 코드에 대해? 왜 데이터를 검색 할 수 없습니까? (btw 첫 번째 코드는 완벽하게 작동하지만 한 번은 아닙니다.) –