我想展示一个我在没有互联网连接时已经创建的自定义组件。
我现在有什么:
- 一个自定义组件,当没有互联网连接时显示。 一个HttpInterceptor来检查我的互联网连接状态。
import { Injectable } from '@angular/core';
import {
HttpRequest,
HttpHandler,
HttpEvent,
HttpInterceptor,
HttpErrorResponse,
HttpResponse
} from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable()
export class ServiceInterceptor implements HttpInterceptor {
constructor() { }
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
req = req.clone(
{
setHeaders: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
}
)
const obs = next.handle(req);
if (!window.navigator.onLine) {
// Handle offline error
// This message is printing correctly :D
console.log("no internet connection");
return;
}
obs.toPromise().catch((error) => {
console.log(error.message);
});
return obs;
}
}
- 一个简单的服务。
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class DataService {
constructor(private httpClient: HttpClient) { }
public sendGetRequest(){
return this.httpClient.get('https://jsonplaceholder.typicode.com/todos/1');
}
}
- 我使用服务的主组件
import { DataService } from '../data.service';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
products = [];
constructor(private dataService: DataService) { }
ngOnInit() {
this.dataService.sendGetRequest().subscribe((data: any[])=>{
console.log(data);
this.products = data;
})
}
}
当有网络连接时,一切都工作正常。
但是我怎么能对我的home组件说没有互联网呢?
我不想检查我的互联网状态在每个组件我有。这就是为什么我检查了httpInterceptor文件。
如果没有这样的网络,你可以路由到你的专用路由
if (!window.navigator.onLine) {
// Handle offline error
// This message is printing correctly :D
console.log("no internet connection");
// Save the current route state
this.router.navigateByUrl('no-internet')
return;
}
你也可以将服务与行为主题结合使用
<<ol>连接服务/gh>
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class ConnectivityService {
isOnline = new BehaviorSubject();
constructor() { }
}
- 拦截
- 然后在Home组件
@Injectable()
export class ServiceInterceptor implements HttpInterceptor {
constructor(private connectivityService: ConnectivityService) {}
intercept(req: HttpRequest < any > , next: HttpHandler): Observable < HttpEvent < any >> {
req = req.clone({
setHeaders: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
})
const obs = next.handle(req);
if (!window.navigator.onLine) {
// Handle offline error
// Update Online status
this.connectivityService.isOnline.next(false)
return;
}
obs.toPromise().catch((error) => {
console.log(error.message);
});
return obs;
}
}
import {
DataService
} from '../data.service';
import {
ConnectivityService
} from 'connectivityService'
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
products = [];
constructor(
private dataService: DataService,
private connectivityService: ConnectivityService) {}
ngOnInit() {
this.connectivityService.isOnline.subscribe(isOnline => {
if (isOnline) {
// Your Logic
}
})
this.dataService.sendGetRequest().subscribe((data: any[]) => {
console.log(data);
this.products = data;
})
}
}