【问题标题】:Angular 4 PouchDB not updating serviceAngular 4 PouchDB 不更新服务
【发布时间】:2017-04-21 11:51:43
【问题描述】:

这是我的服务

export class LunchService {

  private db: any;
  lunches: any = [];

  constructor(
    private serverService: ServerService,
    private configService: ConfigService,
  ) {
    this.db = new PouchDB(configService.config.dbServer + '/' + configService.config.dbName);

    this.db.find({
      selector: { 'type': 'lunch' },
    }).then((result) => {
        // HERE
        this.lunches = result.docs;
    }).catch(function(err) {
      console.log(err);
    });
  }
}

这是我的组件

export class ListingComponent {

  lunches: any = [];

  constructor(
    private lunchService: LunchService
  ) {
    // IS EMPTY WHEN SET IN SERVICE?
    this.lunches = this.lunchService.lunches;
  }
}

为什么午餐服务中对变量的更改没有反映在组件中?控制器中的午餐参数不会被填充。

我猜它不在变化检测中?但是如何做到这一点呢?

【问题讨论】:

    标签: angular2-services pouchdb angular2-components


    【解决方案1】:

    为了解决这个问题,我得到了以下结果。由于服务中的数据将被共享,这似乎是一个令人满意的解决方案,但我不确定它是否是最好的。

    我为 pouch DB 交互提取了一个新服务以返回一个 observable:

    export class PouchDbService {
    
      private db: any;
    
      constructor(
        private configService: ConfigService
      ) {
        this.db = new PouchDB(configService.config.dbServer + '/' + configService.config.dbName);
      }
    
      findDocs(searchParams) {
        return new Observable(observer => {
          this.db.find(searchParams).then((response) => {
            observer.next(response);
          }).catch((err) => {
            console.log(err);
          });
        }
        );
      }
    }
    

    现在在我的午餐服务中,我创建了一个行为主题:

    export class LunchService {
    
      lunches: any = new BehaviorSubject([]);
    
      constructor(
        private pouchDb: PouchDbService
      ) {
        this.getLunches().subscribe((response) => {
          this.lunches.next(response['docs']);
        });
      }
    
      getLunches() {
        return this.pouchDb.findDocs({
          selector: { type: { $eq: 'lunch' } }
        });
      }
    }
    

    最后在我的组件中我再次订阅:

    export class ListingComponent implements OnInit {
    
      lunches: any;
    
      constructor(
        private lunchService: LunchService
      ) { }
    
      ngOnInit(): void {
        this.lunchService.lunches.subscribe((lunches) => {
          this.lunches = lunches;
        });
      }
    
    }
    

    它工作正常,组件更新正常。我只是有点不确定这是否是正确的技术?我应该订阅两次吗?

    通常(非 pouch db / 一般 http 调用)我可以只分配服务变量,而不是行为主体,这可以正常工作并反映组件 / UI 中的任何更改。但是由于小袋使用 a 然后我必须转换为 observable 并以这种方式获取数据。

    有什么想法吗?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-01-19
      • 2018-01-30
      • 1970-01-01
      • 1970-01-01
      • 2018-11-03
      • 2018-07-15
      • 1970-01-01
      相关资源
      最近更新 更多