当observable发出新值时,不会重新加载带有数据和异步管道的简单页面。
我使用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 {}
home.page.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))
);
}
home.page.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())
);
}