2017-11-30 9 views
0

내 Angular2 구성 요소 생성자 저는 Firebase의 값을 변수에 저장합니다.구독에 정의 된 변수가 외부에서 정의되지 않았습니다. (Angular2, Firebase)

this.dbAction.getDB().take(1).subscribe(data => { 
    this.userVisitOrder = data[0][this.currentUserID]['settings']['visitOrder']; 
    console.log(this.userVisitOrder); // Value exists 
}); 

특정 Firebase 데이터를 사용하기 위해 Observable을 구축하려면이 변수가 정확히 필요합니다. 또한 내 생성자 :

this.visitsRef = afDatabase.list('data/users/' + this.currentUserID + '/visits/', ref => ref.orderByChild(this.userVisitOrder)); // Here the value is undefined 

나는 비동기 문제라고 생각하지만 내 변수에 저장된 데이터에 액세스 할 수 있습니까?

dbAction 서비스의 getDb() 함수가 다음과 같습니다

getDB() { 
    return this.afDatabase.list(`data`).valueChanges().map((data) => data); 
} 

을 내가 그렇게 처음으로 두 번째 코드를 삽입하려고하면 :

this.dbAction.getDB().take(1).subscribe(data => { 
    this.userVisitOrder = data[0][this.currentUserID]['settings']['visitOrder']; 

    this.visitsRef = afDatabase.list('data/users/' + this.currentUserID + '/visits/', ref => ref.orderByChild(this.userVisitOrder)); 
    this.visits = this.visitsRef.snapshotChanges().map(changes => { 
    return changes.map(c => ({ key: c.payload.key, ...c.payload.val() })); 
    }); 
}); 

을 ... I 다음 콘솔 오류가 발생합니다.

enter image description here

+0

첫 번째 상황은 확실히 비동기 인 것으로 보입니다. 블록 외부의 수신 거부는 이용할 수 없습니다. 두 번째 문제는 .getDB()가 어떤 이유로 정의되지 않은 것 같습니다. 어떻게 될지이 스 니펫에서 확실하게 알기가 어렵습니다. (즉, .subscribe를 실행하지 못하게되었습니다.) – joelm

+0

내 서비스에서'getDb()'도우미 함수로 내 게시물을 편집했습니다. :) – eleinad

답변

1

관측 자료를 switchMap과 함께 연결하여 다른 하나를 실행하게 할 수 있습니다.

this.dbAction.getDB().take(1) 
    .switchMap(data => { 
     this.userVisitOrder = data[0][this.currentUserID]['settings']['visitOrder']; 

     this.visitsRef = afDatabase.list('data/users/' + this.currentUserID + '/visits/', ref => ref.orderByChild(this.userVisitOrder)); 

     return this.visitsRef.snapshotChanges(); 
    }) 
    .map(changes => { 
     return changes.map(c => ({ key: c.payload.key, ...c.payload.val() })); 
    }); 
    .subscribe(res => {// do something with result}) 
+0

내가 볼 수있는 Observable에 대해'this.visits'를 어디에 선언해야합니까? – eleinad

+0

@eleinad 아 html로 비동기 파이프와 함께 사용하고 있습니까? – LLai

+0

네, 맞습니다! :) – eleinad