因此,我在angular6中使用Observable在用户输入时搜索数据库并返回结果。因此,我将异步管道与Observable一起使用。
要呈现结果,请在我的html中
<div *ngIf='results | async; let items'>
<div *ngFor='let item of items'><button type="button" (click)="getByName(item.id,cepDropValue)" name="button">{{item.name}}</button></div
</div>
results
是可观察到的Observable<SearchResult[]>
,它被定义为this.results = this.nameForm.valueChanges.pipe(...
。
我想要做的就是在单击结果按钮后立即隐藏<div *ngIf='results | async; let items'>...
。因此,每次单击按钮时,在getByName
函数中我该怎么做?
我从rxjs
中导入了空内容,并尝试了类似的操作
getByName(id,cep){
this.results = EMPTY; //also tried '' and false
this.mapcmsService.getById(id,cep).subscribe((data) =>{
//grab the data
})
}
这不起作用。我必须以某种方式清空results
,以便隐藏
div
。有任何想法吗?
谢谢
答案 0 :(得分:1)
为您的需要,我将建议另一种方法,但这可能不是最好的方法。
我将在组件打字稿文件中订阅您可观察的内容,而不是在模板中使用private results$: Observable<any>;
private isAlive = true;
private items= any[];
public ngOninit(){
this.results$
.takeWhile(() => this.isAlive)
.subscribe((res) => {
this.items = res;
});
}
public ngOnDestroy(){
this.isAlive = false;
}
private removeFromArray(element) {
const index = this.items.indexOf(element);
if (index > -1) {
this.items.splice(index, 1);
}
}
private getByName(item, cepDropValue) {
// if this is an http request, then you can keep the subscription like that.
// Otherwise, use the takeWhile() to unsubscribe automatically on
// component destruction
this.removeFromArray(item); // delete
this.mapcmService.getById(item.id, cepDropValue)
.subscribe(() =>
// grab data
);
}
。
(请用您的特定类型替换下面的任何类型)
your-class.component.ts
<div *ngFor='let item of items'>
<button type="button"
(click)="getByName(item, cepDropValue)"
name="button" />
<span>{{item.name}}</span>
</div>
your-class.component.html
MySettingsForm {
signal notify()
onNotify: {
mainApp.notifyMe();
}
Component.onCompleted: {
var cbs = [Combobox1, Combobox2, Combobox3];
for (var i in cbs) {
cbs[i].checkedChanged.connect(notify);
}
var sbs = [SpinBox1, SpinBox2, SpinBox3];
for (i in sbs) {
sbs[i].valueChanged.connect(notify);
}
var tes = [TextField1, TextFiel2, TextField3];
for (i in tes) {
tes[i].textChanged.connect(notify);
}
var cxs = [ComboBox1, ComboBox2, ComboBox3];
for (i in cxs) {
cxs[i].currentIndexChanged.connect(notify);
}
}
...
}