Hello I have a PouchDB service that retrieves some data and return a promise with it. I want to convert that promise to an observable and then subscribe in ngOnInit so the model gets updated.
I made an implementation of a service with a method that returns the observable, but it's not working (the data does not get reflected on DOM):
Component HTML:
<h1>{{title}}</h1>
<ul>
<li *ngFor="let platform of platforms">
<a href="#">{{ platform }}</a>
</li>
</ul>
Component TS:
import { Component, OnInit } from '@angular/core';
import { PouchDbBuilder } from './PouchDbBuilder';
import { PlatformsService } from './services/PlatformsService';
@Component({
selector: 'platforms',
templateUrl: './platforms.component.html'
})
export class PlatformsComponent implements OnInit {
title : string;
platforms: Array<string>;
private platformsService;
constructor() {
this.title = "All Platforms";
let serviceName = 'http://xxxx.net:5984/';
let pouchDbBuilder = new PouchDbBuilder(serviceName);
this.platformsService = new PlatformsService(pouchDbBuilder);
}
ngOnInit() {
this.platformsService.getPlatforms().subscribe(platforms => {
this.platforms = platforms;
});
}
}
Service TS:
import { Injectable } from '@angular/core';
import {PouchDbBuilder} from './PouchDbBuilder';
import {PlatformsDataProvider} from './PlatformsDataProvider';
import { Observable } from "rxjs/Observable";
@Injectable()
export class PlatformsService {
private platformsProvider;
constructor(private pouchDbBuilder: PouchDbBuilder) {
this.platformsProvider = new PlatformsDataProvider(this.pouchDbBuilder);
}
getPlatforms(): Observable<Array<string>> {
return new Observable(observer => {
this.platformsProvider.getPlatforms().then(platforms => {
observer.next(platforms);
}).catch(err => {
console.error(err);
});
});
}
}
This only works if i add "this.ngZone.run" after the suscribe to the ngOnInit, like this:
ngOnInit() {
this.platformsService.getPlatforms().subscribe(platforms => {
this.ngZone.run(() => {
this.platforms = platforms;
});
});
}
But this way it's like cheating because i'm forcing the update on DOM.
Can anyone tell me what i'm doing wrong?