如何在 Angular 7 中 ping IP 地址 [英] How to ping IP Address in Angular 7

查看:33
本文介绍了如何在 Angular 7 中 ping IP 地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过获得某种响应或黑客攻击来 ping IP 地址以获取响应,无论它是否存在.

I want to ping IP Address to get response either it is alive or not by getting some sort of response or hack.

ping() {
    return this.http.get('http://192.168.2.101')
}

this.deviceService.ping().subscribe(result => {
    console.log(result)
})

但我收到此错误.

推荐答案

这里是一个例子,如果有人必须从客户端做这件事,一个用例可能是如果你必须 知道客户端是否在线,例如在 Ionic 应用程序中.

Here is an example if anyone has to do it from the client, one use case could be if you must know wether the client is online or not, for example in a Ionic app.

请参阅 this 中的完整工作示例StackBlitz(您也可以检查控制台以查看每次 ping 尝试).

Please see full working example in this StackBlitz (You can check the console also to see each ping attempt).

import { HttpClient } from "@angular/common/http";
import { first } from "rxjs/operators";
import { Subscription } from 'rxjs';
...

private source = interval(3000);
...

this.source.subscribe(() => {
  this._http.get('https://www.google.com', { observe: 'response' })
  .pipe(first())
  .subscribe(resp => {
    if (resp.status === 200 ) {
      console.log(true)
    } else {
      console.log(false)
    }
  }, err => console.log(err));
});

first() 只取第一个值很重要,因为间隔会产生新的请求,这就是我们避免内存泄漏的方法.

first() is important to take only first value, since interval will make new request this is how we avoid memory leaks.

{ observe: 'response' } 是我们告诉 httpClient 返回完整的 http 对象而不是单独的正文的方式,这样我们就可以访问状态代码.

{ observe: 'response' } is how we tell httpClient to return the full http object instead of the body alone, this way we can acces status code.

这篇关于如何在 Angular 7 中 ping IP 地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆