[英]Angular2 form control valueChanges observable complete never called
我正在嘗試在搜索欄上顯示一個簡單的加載器,同時進行搜索。 我已計划在valueChanges
observable的subscribe回調中將一個變量從我的表單控件設置為值“loading”,並在完整的回調中將其設置為空字符串。 但是,永遠不會調用完整的回調。
我也嘗試在observable上添加一個回調函數,但它也從未調用過。
我的代碼:
searchBox: Control = new Control();
loadingClass: string = "";
constructor() {
this.searchBox.valueChanges
.debounceTime(400)
.distinctUntilChanged()
.subscribe((text: string) => {
this.imageSearch = text;
this.loadingClass = "loading";
}, (err: Error) => {
console.log(err);
}, () => {
this.loadingClass = "";
console.log("test");
});
}
這是正常的,因為觀察結果永遠不會完成。 valueChanges
允許您從搜索框中接收值。 實際上,您希望在搜索操作完成時收到通知。
所以我會嘗試類似的東西,假設searchImage
實際上進行搜索並返回一個observable:
constructor() {
this.searchBox.valueChanges
.debounceTime(400)
.distinctUntilChanged()
.flatMap((text:string) => { // <-------
this.loadingClass = "loading";
return this.searchImage(text);
})
.subscribe((searchResult) => {
this.imageSearch = searchResult;
this.loadingClass = ""; // <----
}, (err: Error) => {
console.log(err);
});
}
有關flatMap
運算符的用法,請參閱此文章:
我發現我正在嘗試錯誤的做法。 相反,我意識到我有debounceTime
我觀察到的,所以我注冊了一個keyup
我輸入控制事件,並在其設置的值loadingClass
以"loading"
,在我的訂閱我設置的值回一個空字符串。
我希望這可以讓一些人更好地理解Angular2 Forms。 Angular有兩種不同的構建形式的方法(Reactive和Template形式)。 沒有意識到這可能會導致你的應用程序混亂。
valuesChages是指令NgModel和FormControl類的屬性(請記住)。
被動方法使用
ReactiveFormsModule import
(your.module.ts):
import {ReactiveFormsModule} from '@angular/forms';
@NgModule({
...
imports: [
...
ReactiveFormsModule,
...
],
...
})
通過這種方式,您可以在窗體控件(template.component.html)上使用[(formControl)]
屬性。
<input type="text" class="form-control" id="searchBox"
required
[(formControl)]="searchBox"/>
接近模板驅動(your.module.ts):
import {FormsModule} from '@angular/forms';
@NgModule({
...
imports: [
...
FormsModule,
...
],
...
})
這個接近它有自己的表單控件屬性, ngModel (your.template.ts):
<input type="text" class="form-control" id="searchBox"
required
[(ngModel)]="searchBox"/>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.