我需要在每个页面中调用wifi的连接状态。 然后使用提供程序,但在MyApp(app.component.ts)构造函数中,仅调用一次提供程序(ConectivityServiceProvider)。
app.component.ts
import { ConectivityServiceProvider } from '...'
import { Network } from '.....';
export class MyApp {
conectivity:boolean
constructor(private provider: ConectivityServiceProvider,public network: Network){
platform.ready().then(() => {
this.conectivity=provider.isOnline();
// call once in all pages
if(this.conectivity){
//do someting
}else //do something
}
}
}
提供者:
@Injectable()
export class ConectivityServiceProvider {
statusConectivity: boolean =true;
constructor(public network: Network){
this.network.onDisconnect().subscribe(() => {
this.statusConectivity=false;
});
}
isOnline(){
return this.statusConectivity;
}
}
如果我将所有内容都放在MyApp类的提供程序中,它会在每个页面中调用,而不仅仅是一次。 为什么只使用提供商一次呼叫一次?
答案 0 :(得分:1)
您应该选中Ionic lifecycle events
从您的描述看来,您有3种选择:
因此,根据您在断开连接时的处理方式,可以使用 ionViewDidLoad 检查页面的每次初始加载,或使用 ionViewWillEnter 每次进行检查显示页面(包括例如后退操作)。
app.component.ts
中的代码如下:
import { ConectivityServiceProvider } from '...'
import { Network } from '.....';
export class MyApp
{
conectivity: boolean;
constructor(private provider: ConectivityServiceProvider, public network: Network)
{
platform.ready().then(() =>
{
});
}
ionViewDidLoad()
{
this.conectivity = provider.isOnline();
// call once in all pages
if(this.conectivity)
{
//do someting
}
else //do something
{
}
}
}
答案 1 :(得分:1)
请尝试angular的HttpInterceptor
拦截器拦截应用程序中的每个API调用。因此,在每个API调用之前,我们可以检查连接状态并相应地处理代码。
引用:Capture requests globally in angular 4 and stop if no internet
import { Injectable } from '@angular/core';
import {
HttpRequest,
HttpHandler,
HttpEvent,
HttpInterceptor
} from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class ConectivityServiceProvider implements HttpInterceptor {
constructor() { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// check to see if there's internet
if (!window.navigator.onLine) {
// if there is no internet, throw a HttpErrorResponse error
// since an error is thrown, the function will terminate here
return Observable.throw(new HttpErrorResponse({ error: 'Internet is required.' }));
} else {
// else return the normal request
return next.handle(request);
}
}
}