как я могу прочитать данные из базы данных - PullRequest
0 голосов
/ 15 января 2019

Я пытаюсь отправить данные в базу данных firebase по userId, даже у каждого пользователя, которого он может изменить, есть публикация или информация. отправленные данные успешно, но проблема в том, когда я пытаюсь получить данные в html дозе не показывать.

база данных

enter image description here

HTML

enter image description here

код для получения данных:

items: Observable<any[]>;
itemsRef: AngularFireList<any>;
  constructor(public fire: AngularFireAuth,public db: AngularFireDatabase) 
    {
        this.itemsRef = db.list(`report/`);
        // Use snapshotChanges().map() to store the key
        this.items = this.itemsRef.snapshotChanges().pipe(
          map(changes => 
            changes.map(c => ({ key: c.payload.key, ...c.payload.val() }))
          )

        );

      }

HTML

 <ion-list *ngFor="let item of items | async"> 
    <ion-item-sliding>
      <ion-item>
        <h2>{{itemstitle}}</h2>
        <p>{{item.name}}</p>
        <p>{{item.username}}</p>
        <p>{{item.dateadded}}</p>
    </ion-item>

      <ion-item-options side="right"> 
        <button ion-button color="danger" (click)="deletReport(item.key)">
          <ion-icon  ios="ios-trash" md="md-trash" item-end large></ion-icon>
        </button>
        <button ion-button color="primary" (click)="updatereport(item.key,item.name,item.title)">
          <ion-icon ios="ios-create" md="md-create"></ion-icon>
        </button>
      </ion-item-options>

    </ion-item-sliding>
  </ion-list>

мои данные push:

name :string='';
  title :string='';
  Email:string='';
  dateadded:string='';
  userId: string;

  reports: AngularFireList<any>;
  items: Observable<any[]>;

  constructor(db: AngularFireDatabase,public alertCtrl: AlertController,public loadingCtrl: LoadingController,
    public navCtrl: NavController,public fire: AngularFireAuth) {
     var newPostKey = db.database.ref().child('report').push().key;
    this.reports = db.list(`report/${this.userId=fire.auth.currentUser.uid}/`);

    console.log(this.userId=fire.auth.currentUser.uid)

  }

  formatDate (date): string{

    const day = new Date().getDate();
    const month = new Date().getMonth()+1;
    const year = new Date().getFullYear();
    return `${day}-${month}-${year}`
  }
// dateaddread(dateadded){
//   this.dateadded = this.formatDate(dateadded)
// }

  Publish(name,title,dateadded){
    if (name.trim().length === 0) {
      console.log(this.name);
      let alert = this.alertCtrl.create({
        title: 'Error',
        message: 'Please fill report blank ',
        buttons: ['OK']
    });
    alert.present(); 
    }else if (title.trim().length === 0){

      let alert = this.alertCtrl.create({
        title: 'Error',
        message: 'Please fill title blank ',
        buttons: ['OK']
    });
    alert.present(); 
    }else {

      this.reports.push({
        name:name,
        title:title,
        Email:this.fire.auth.currentUser.email,
        dateadded:this.formatDate(dateadded)

      }).then(Newreport=>{
        let alert = this.alertCtrl.create({
          title: 'Successful',
          message: 'Successfully posted',
          buttons: [
            {
              text: 'Ok',
              handler: () => {
            let navTransition = alert.dismiss();
            // start some async method
            navTransition.then(() => {
            this.navCtrl.pop().then(data => {
            this.navCtrl.setRoot(FeedPage)

            });
       });
      return false;
    }
    }]          
    });

      alert.present()

      })
    }

    }

любая идея, пожалуйста, с простым кодом?

1 Ответ

0 голосов
/ 16 января 2019
this.reports = db.list(`report/${this.userId=fire.auth.currentUser.uid}/`);

this.reports.push({
    name:name,
    title:title,
    Email:this.fire.auth.currentUser.email,
    dateadded:this.formatDate(dateadded)
})

и для отображения данных в HTML вам просто нужно изменить запрос, чтобы получать только данные вошедшего в систему пользователя

this.itemsRef = db.list(`report/` + fire.auth.currentUser.uid);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...