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

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

问题描述

我想通过获取某种响应或破解来对IP地址执行ping操作,以获取响应是否存在的信息.

  ping(){返回this.http.get('http://192.168.2.101')}this.deviceService.ping().subscribe(result => {console.log(结果)}) 

但我收到此错误.

解决方案

下面是一个示例,如果有人必须从客户端执行此操作,则一个用例是您必须知道客户端是否在线,例如在Ionic应用程序中.

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

 从"@ angular/common/http"导入{HttpClient};从"rxjs/operators"导入{first};从'rxjs'导入{订阅};...私人来源=间隔(3000);...this.source.subscribe(()=> {this._http.get('https://www.google.com',{观察:'response'}).pipe(first()).subscribe(resp => {如果(resp.status === 200){console.log(true)} 别的 {console.log(false)}},err =>console.log(err));}); 

first()对于仅获取第一个值很重要,因为interval将发出新请求,这是我们避免内存泄漏的方式.

{观察:'response'} 是我们告诉 httpClient 返回完整的http对象而不是仅返回正文的方式,这样我们可以获取状态代码./p>

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)
})

but I am getting this error.

解决方案

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.

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() is important to take only first value, since interval will make new request this is how we avoid memory leaks.

{ 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天全站免登陆