【问题标题】:How to move database-related code to a separate service?如何将与数据库相关的代码移动到单独的服务中?
【发布时间】:2018-02-09 12:09:01
【问题描述】:

我是 Angular 和 Ionic 的新手。我已经启动了一个简单的应用程序,可以将项目添加到 Firebase Db。到目前为止一切顺利。

我的组件 ts 文件中有两种方法:

add(item: string) {
  this.items.push({
    item: item
  })
  .catch(error => console.log('ERROR ' + error));
}

remove(key: string) {
  this.af.object( `/items/${key}`).remove()
    .catch(error => console.log('ERROR ' + error));
}

我想把上面的方法移到一个单独的服务类中,所以我新建了一个文件:

import {Injectable} from "@angular/core";

@Injectable()
export class ItemService {
   constructor() {
   }
}

但是上面的方法引用了items,这是一个FirebaseListObservable,af是一个注入控制器的AngularFireDatabase。

如何修改以上2个方法,使其可以在服务中移动?

【问题讨论】:

    标签: angular firebase ionic-framework firebase-realtime-database angularfire


    【解决方案1】:

    当您启动并定义这些方法时,白一个可注入服务。然后 firebase db 将返回一个 observable,在您的服务中,您可以处理这些数据,然后再次返回 observable,它可以订阅以使用和处理视图

    @Injectable()
    export class ItemService {
       constructor(private firebaseService: FirebaseService) {
       }
    
    add(item: string) {
    
      // if firebase service returns observable, then map will precess and return observable whcih can be subscribed
      this.fireBaseService.get().map( (data) => {
         return this.items.push({
           item: data.item
        })
         .catch(error => console.log('ERROR ' + error));
      })
    }
    
    
    // same f0r remove
    remove(key: string) {
       return this.af.object( `/items/${key}`).remove()
        .catch(error => console.log('ERROR ' + error));
    }
    }
    // if I understood the question correctly
    

    【讨论】:

      猜你喜欢
      • 2019-12-29
      • 2021-02-12
      • 2011-05-10
      • 1970-01-01
      • 1970-01-01
      • 2010-09-24
      • 1970-01-01
      • 2018-11-19
      • 2021-09-15
      相关资源
      最近更新 更多