2017-09-26 4 views
0

내 프로젝트에서는 Ionic 3과 AngularFire2를 사용하고 있습니다. firebase 데이터베이스에서 값을 가져 와서 일부 변경 작업을 수행하고 HTML 페이지에 표시해야 구독이 완료 될 때까지 기다려야합니다. 여기 내 코드입니다 :Angularfire2, Ionic 3에서 Subscription 대신 Map을 사용하는 방법

items: FirebaseListObservable<any[]>; 

constructor(public navCtrl: NavController, public afDB: AngularFireDatabase) {} 

async ionViewDidEnter(){ 

    var a = await this.calldatabase(); 
    console.log(a);  // it display first and value is undefined 
    console.log('3');  // it display second 
} 

async calldatabase(){ 

    let category: any; 
    this.items = this.afDB.list('/cat', { preserveSnapshot: true }); 
    await this.items.subscribe(snapshots => { 
    snapshots.forEach(snapshot => { 
     console.log(snapshot.val());  // it displays third 
     category = snapshot.val(); 
    }); 
    }); 
    return category; 
} 

`

내가 가입이 완료 될 때까지 기다립니다 수 없습니다, 그때 나는 그것을 봤 후 다음 링크를

Angular 2 Wait for subscription to complete

angularfire2 wait for subscription to end?

발견

How to wait for a AngularFire2 subscription to finish before running the next lines of code Angular2

해결할 수 없습니다. 이제 필자는 아무것도에게

import 'rxjs/add/operator/map'; 

async calldatabase(){ 

    let category: any; 
    this.items = this.afDB.list('/cat', { preserveSnapshot: true }); 
    await this.items.map(snapshots => { 
    console.log(snapshots);    // it displays nothing 

    snapshots.forEach(snapshot => { 
     console.log(snapshot.val());  // it displays nothing 
     category = snapshot.val(); 
    }); 
    }); 
    return category; 
} 

My Cat value in database

답변

0
this.afDB.list('/cat', { preserveSnapshot: true }); 

이것은 당신이 구독 할 수있는 감시 오브젝트입니다 표시되지 않는 대신 가입의 맵을 사용하려고합니다. 당신이 데이터

showMyData(){ 

this.callDatabase.subscribe((data)=>{ 
//Do something with this data 
console.log(data)}); 

} 

난 당신이 중포 기지에 대한 서비스와 고양이에 대한 모델을 사용하는 것이 좋습니다

을 필요로하는 곳에

async calldatabase(){ 


    return this.afDB.list('/cat', { preserveSnapshot: true }); 

} 

는 그런 다음 구성 요소에이 문을 사용할 수 있습니다. 는 다음과 같은 코드를 사용할 수 있습니다

showMyData(){ 

let theCats: Cats[]; 

this.callDatabase.subscribe((data)=>{ 
theCats = data; 
console.log(theCats)}); 

//Do something with theCats 
} 
+0

내가 그것을했다,하지만 그것은 – LucidKit

+0

어쩌면 당신은 당신이 지금까지 가지고있는 코드를 게시 할 수 있습니다 작동하지 않습니다. – hsc