【发布时间】:2020-03-18 10:22:36
【问题描述】:
card.service.ts
@Injectable({
providedIn: 'root'
})
export class CardService {
drugs: Drugs = [];
public objObservable: any;
private objObserver: any;
constructor() {
this.objObservable = new Observable((localObserver) => {
this.objObserver = localObserver; // Convert this.objObserver from any to an observer object
this.objObserver.next(this.drugs); // Connect this.drugs to observable object by observer
});
}
getDrugs(): Observable<Drugs> {
return this.objObservable;
}
addDrug(newDrug: Drug) {
this.drugs = [...this.drugs, newDrug];
return this.objObserver.next(this.drugs);
}
removeDrug(neo4jId: string) {
this.drugs = this.drugs.filter((item: Drug) => item.neo4jId !== neo4jId);
return this.objObserver.next(this.drugs);
}
我正在使用此服务在我的 Home 组件中的 Observable 中添加和删除一些药物。 在卡片组件中,我想在这个 Observable 中循环并给出我需要在 html 中显示的值。
card.component.html
<div>
{{ this.cardService.getDrugs() | async | json }}
</div>
这个给了我所有 observable 的输出为 json,然后我尝试做类似的事情
<div>
{{ (this.cardService.getDrugs() | async | json).type }}
</div>
只显示类型,但这不起作用。 我怎样才能遍历这个 observable 中的所有对象并只输出 f.e. 的类型?
药物型号:
export interface Drug {
neo4jId?: string;
drugId?: string;
tradingName: string;
type: string;
quantity: number;
expire: Date;
entryDate: Date;
lastModified?: Date;
slot: number;
substances?: Substance[]
};
export interface Drugs extends Array<Drug> { }
【问题讨论】:
-
有点不清楚。
drugs: Drugs = [];是Drugs类型的数组。或者它是否意味着drugs = Drug[]是Drug类型的数组?
标签: angular asynchronous observable