我有一个搜索引擎,用户可以在其中通过多个标签搜索毒品。
<tbody *ngFor="let result of searchResults.content | slice:0:99">
<tr>
<td>{{result.slot.number}}</td>
<td>{{result.tradingName}}</td>
<td>
<p *ngFor="let subs of result.substances">{{subs.dose}}{{subs.entity}},
{{subs.substance.substanceName}}</p>
</td>
<td>{{result.type}}, {{result.quantity}}</td>
<td>{{birthdayToString(result.expire)}}</td>
<td>{{result.entryDate}}</td>
<td><button (click)="addToCard()" class="btn btn-success ml-1">Add</button></td>
</tr>
</tbody>
在添加时,用户应该可以选择将此对象添加到列表中,然后使用存储在其他组件的Observable中的该对象。
此html的ts文件:
constructor(private http: HttpClient, private drugService: DrugsService, private router: Router, private cardService: CardService) {
this.searchTerm.pipe(
map((e: any) => e.target.value),
debounceTime(700),
distinctUntilChanged(),
filter(term => term.length >= 1)
).subscribe(searchTerm => {
this.loading = true;
this._searchEntries(searchTerm);
});
}
ngOnInit() {
this.fetchDrugs();
}
searchEntries(term: any): Observable<any> {
return this.http.get(this.drugSearch + term).pipe(
map(response => {
this.searchResults = response;
// console.log(response);
})
)
}
addToCard() {
this.cardService.addDrug(({
tradingName: "Depon",
type: "Pill",
quantity: 22,
expire: new Date(),
entryDate: new Date(),
slot: 5
}));
}
现在在我的ts文件中,我正在addToCard()中对药物进行硬编码。
但是我想传递用户单击的对象,而不是硬编码的对象。我该怎么办?
卡服务:
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);
}
clear() {
this.drugs = [];
this.objObserver.next.this.drugs;
}
}
我想使用此服务和addDrug函数来传递对象并将其放入Observable,但是如何?
这是我的毒品模型,以备您需要时了解:
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> { }
将result
发送到事件处理程序中。尝试以下]]
模板
<button (click)="addToCard(result)" class="btn btn-success ml-1">Add</button>
组件
addToCard(drug: Drug) {
this.cardService.addDrug(drug);
}