【发布时间】:2021-10-18 19:45:58
【问题描述】:
我想展示一个我在没有互联网连接时已经创建的自定义组件。
到目前为止我有什么:
- 在没有互联网连接时显示的自定义组件。
- 一个用于检查我的互联网连接状态的 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;
})
}
}
只要有互联网连接,一切都会正常工作。
但是我怎么能说我的 HomeComponent 没有互联网呢?
我不想在我拥有的每个组件中检查我的互联网状态。这就是我检查 httpInterceptor 文件的原因。
【问题讨论】:
标签: angular typescript