[英]In Ionic 4, an observable from a store selector doesn’t refresh the UI ! Why?
當 observable 發出新值時,不會重新加載帶有數據和異步 pipe 的簡單頁面。
我用 Ionic CLI 創建了一個空白頁面。 我添加了網絡插件。 在主頁中,我監聽網絡更改,控制台記錄更改但 UI 未刷新……
app.module.ts
@NgModule({
declarations: [AppComponent],
entryComponents: [],
imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule],
providers: [
StatusBar,
SplashScreen,
{ provide: RouteReuseStrategy, useClass: IonicRouteStrategy },
Network
],
bootstrap: [AppComponent]
})
export class AppModule {}
主頁.ts
test$: Observable<string>;
constructor(private network: Network) {}
/**
*
*/
ngOnInit(): void {
this.test$ = concat(
this.network.onConnect().pipe(debounceTime(2000)),
this.network.onDisconnect()
).pipe(
tap(() => console.log('Connection changed !')),
map(() => this.network.type),
tap(type => console.log('Connection type', type))
);
}
主頁.html
<ion-header>
<ion-toolbar>
<ion-title>
Ionic Blank
</ion-title>
</ion-toolbar>
</ion-header>
<ion-content>
<div class="ion-padding">
The world is your oyster.
<p *ngIf="test$|async as test">{{test}}</p>
</div>
</ion-content>
我使用ionic cordova run android -lcs
應用程序(在我通過 USB 連接的設備上)
我通過禁用wifi來更改網絡類型。 控制台日志:
Connection changed !
home.page.ts:26 Connection type 4g
UI沒有刷新……怎么了???
必須自己測試以確認我的懷疑,即該插件在 Angular 更改檢測之外運行。 因此,即使將值分配給字符串變量,例如...
this.network.onConnect().pipe(
map(() => this.network.type)
).subscribe(type => this.test$ = type)
並用{{ test$ }}
顯示不起作用
因此,我們可以通過導入ChangeDetectorRef
手動觸發更改檢測,將其注入構造函數並調用detectChanges()
:
import { ChangeDetectorRef } from '@angular/core';
// ...
constructor(
private network: Network,
private cdr: ChangeDetectorRef
) { }
ngOnInit(): void {
this.test$ = concat(
this.network.onConnect().pipe(debounceTime(2000)),
this.network.onDisconnect()
).pipe(
map(() => this.network.type),
tap(() => this.cdr.detectChanges())
);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.