你好,我有一個PouchDB服務,它檢索一些數據並返回一個承諾。我想將該承諾轉換爲可觀察的,然後在ngOnInit中訂閱,以便模型得到更新。Angular 4使用訂閱綁定數據從一個可觀察的不起作用的承諾
我做了一個返回觀察到的方法的服務的實現,但它不工作(該數據不會反映在DOM):
組件的HTML:
<h1>{{title}}</h1>
<ul>
<li *ngFor="let platform of platforms">
<a href="#">{{ platform }}</a>
</li>
</ul>
組件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;
});
}
}
服務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.ngZone.run」的suscribe到ngOnInit後,像這樣的工作:
ngOnInit() {
this.platformsService.getPlatforms().subscribe(platforms => {
this.ngZone.run(() => {
this.platforms = platforms;
});
});
}
但是這樣一來它像欺騙,因爲我強迫DOM上的更新。
誰能告訴我我做錯了什麼?
什麼是袋分貝建設者在這裏拍攝,你能不能直接調用HTTP GET返回一個可觀察到的由defualt –
PouchDbBuilder是一個自定義庫,做出自己的HTTP調用,使用Xhr庫,而不是Angular http。 PlatformsDataProvider也一樣。 – CoF