使用异步将 Observable 绑定到模板
Bind Observable to template using async
我试图通过以下方式将 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(() => { });
我尝试过不同的 Observable,也尝试过 Promise 但没有将它变成 Observable,但我无法让它工作。
因为 promises 只会触发一次,您不会再收到通知。唯一的方法是像这样将 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 }));
}
}
我试图通过以下方式将 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(() => { });
我尝试过不同的 Observable,也尝试过 Promise 但没有将它变成 Observable,但我无法让它工作。
因为 promises 只会触发一次,您不会再收到通知。唯一的方法是像这样将 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 }));
}
}