Ionic 在Angular 11中检测到无互联网连接

q1qsirdb  于 2022-12-16  发布在  Ionic
关注(0)|答案(2)|浏览(159)

我在这里的主要目标是检测互联网连接是否活跃或不在我的网站。
以下代码行在我的http://localhost:8100/中是有效的,但不幸的是,当我在Heroku中部署我的网站时,所有这些检测Internet连接的功能都失败了。

**此Ion警报控制器检测网络连接是否处于活动状态。**但不幸的是,部署后,此警报在我的系统中没有响应。如果未检测到连接,则必须调用警报控制器。

如果用户按下RELOAD(重新加载),整个页面将再次重新加载,以检查是否存在连接:

这是检测网络连通性的代码。我使用了这个例子:https://stackoverflow.com/a/57069101/13848366

应用程序组件.ts

注:我将createOnline$设置为Observable,以便自动检测连接是否发生变化。

connectionMsg: boolean;

  constructor(private alertController: AlertController) {

    this.createOnline$().subscribe(isOnline => {
      console.log(isOnline);
      if (isOnline == true) {
        this.connectionMsg = true;
      } else {
        this.connectionMsg = false;
        this.reloadPage();
      }
      console.log("Msg: " + this.connectionMsg);
    })

  }

  createOnline$() {
    return merge<boolean>(
      fromEvent(window, 'offline').pipe(map(() => false)),
      fromEvent(window, 'online').pipe(map(() => true)),
      new Observable((sub: Observer<boolean>) => {
        sub.next(navigator.onLine);
        sub.complete();
      })
    );
  }

  //THIS IS THE ION ALERT CONTROLLER WITH window.location.reload() to reload the whole page.
  async reloadPage() {
    const alert = await this.alertController.create({
      header: 'Connection Lost',
      message: 'Try to <strong>reload</strong> the page.',
      backdropDismiss: false,
      buttons: [
        {
          text: 'Reload',
          handler: () => {
            window.location.reload();
          }
        }
      ]
    });

    await alert.present();
  }
zd287kbt

zd287kbt1#

可能这会有所帮助:

import {HostListener} from '@angular/core';
@HostListener('window:online', ['$event'])
onLine(e:any){
 // do something
}
hm2xizp9

hm2xizp92#

您可以尝试使用官方的plugin表示离子,例如:

NO INTERNET COMPONENT.TS
    import { Network } from '@ionic-native/network/ngx';

    constructor(
        private router: Router,
        private network: Network, 
        private dialog: DialogService,
        public translate: TranslateService) { }
    
      tryAgain() {
        const networkState = this.network.type;
    
        if (networkState !== this.network.Connection.NONE) {
          this.router.navigate(["/tabs/marketplace/"], { replaceUrl: true });
        }
        else {
          this.dialog.showAlert(HeaderTypes.NOTIFICATION, this.translate.instant("ERRORS.STILL_NO_CONNECTION"), ['ok']);
        }
    
      }

应用拦截器.TS

export class Http_Interceptor implements HttpInterceptor{
   ...

  intercept(req: HttpRequest<any>, next: HttpHandler) {

        this.disconnectSubscription = 
         this.network.onDisconnect().subscribe((res) => {
            //this.router.navigate(['no-internet']);
            return res.returnValue;
        });

        if (this.disconnectSubscription !== true) {
            ...

            if (token != null) {
               ...
                })
            }
            return next.handle(authReq).pipe(
                map((event: HttpEvent<any>) => {
                    if (event instanceof HttpResponse) {
                        //silence its golden
                    }
                    return event;
                }),
                catchError((error: HttpErrorResponse) => {
                    switch (error.status) {

                        case 0:
                            this.router.navigate(['no-internet']);
                            break;
                       ... ect
                    }

                    return throwError(error);
                }), share());
        }

        else {
            this.router.navigate(['no-internet']);
        }

    }
}

相关问题