我试图通过执行以下操作将Observable绑定到Angular中的模板变量:
[class.active]="isBookmarked$ | async"
在ngOnInit中,我设置了Observable:
var promise = this.cacheService.getItem(this.bookmarkId).then(() => {
return true;
}).then(() => {
return false;
});
this.isBookmarked$ = Observable.fromPromise(promise);
加载页面时工作正常。但是当我添加或删除项目时,模板无法识别更改检测。
this.cacheService.removeItem(this.bookmarkId).then(() => { });
// or
this.cacheService.saveItem(this.bookmarkId, true, "bookmarks").then(() => { });
我尝试了不同的Observables并尝试了Promise而没有使它成为Observable,但是我无法让它工作。
答案 0 :(得分:2)
由于承诺只会在您再次收到通知后触发。唯一的方法是将cacheService包装到一个新服务中(如果你不能更改原始服务),如下所示:
import { Subject } from "rxjs/Subject";
import "rxjs/add/operator/filter";
import "rxjs/add/operator/map";
import { Injectable } from '@angular/core';
interface CacheService
{
getItem(key: any): Promise<any>;
setItem(key: any, value: any): Promise<any>;
}
interface Item
{
key: any;
value: any;
}
@Injectable()
export class ObservableCacheService
{
protected readonly items$ = new Subject<Item>();
constructor(protected readonly cacheService: CacheService) { }
getItem(key: any)
{
this.cacheService
.getItem(key)
.then(value => items$.next({ key: key, value: value }));
return items$
.filter(item => item.key === key)
.map(item => item.value);
}
setItem(key: any, value: any)
{
this.cacheService
.setItem(key, value)
.then(() => items$.next({ key: key, value: value }));
}
}