在Ionic 4中,从商店选择器中观察到的内容不会刷新UI!为什么?

时间:2019-10-25 14:08:59

标签: angular ionic4 ngrx angular-changedetection

当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

用户界面未刷新... 怎么了???

1 个答案:

答案 0 :(得分:0)

必须自己进行测试以确认我的怀疑,这是因为该插件在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())
  );
}
相关问题