2017-04-21 83 views
0

这里是我的服务角4 PouchDB没有更新服务

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; 
    } 
} 

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

我猜它不是在变化检测?但如何使这项工作?

回答

1

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

我提取袋数据库交互的新的服务来回报可观察到的:

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; 
    }); 
    } 

} 

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

一般(非袋DB /普通HTTP调用)我可以指定服务变量,而不行为主体,而这将很好地工作,并反映在组件/ UI的任何变化。但随着袋使用一个然后我不得不转换为可观察并获得数据的方式。

有什么想法?