我需要在每个页面中调用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类中,它确实会调用每个页面,而不是只调用一次。为什么使用提供程序只调用一次?
发布于 2018-09-19 17:49:38
您应该选中离子lifecycle events
从你的描述看,loke你有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
{
}
}
}发布于 2018-09-20 20:58:36
请尝试angular的HttpInterceptor
拦截器截取app.So中的每个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);
}
}
}https://stackoverflow.com/questions/52399232
复制相似问题