【问题标题】:Get data from http request in Angular 5从Angular 5中的http请求获取数据
【发布时间】:2018-05-10 20:44:30
【问题描述】:

我正在尝试使用 nodejs、expressjs 和 Angular 5 构建一个小型服务器监视器/控制台。为了确定 apache 服务是否在远程服务器上运行,我构建了一个后端脚本,它试图从我要控制的服务器。问题是,我不知道如何从角度返回中获取http.get 的数据。在下面的示例中,我尝试将变量 this.apacheRunning 设置为 http.get 请求的响应。非常感谢您的帮助!

getApacheRunning(): Observable<String>{

    this.apacheRunning = this.http.get("http://localhost:3000/ison").subscribe(result => this.apacheRunning = result,(err) => console.log(err), ()=> console.log("done"));
    console.log(this.result);

    if(this.apacheRunning == "true"){
      console.log(this.apacheRunning + "DEBUG2");
      return of("true");
    }else{
      console.log(this.apacheRunning + "DEBUG1");
      return of("false")
    }



}

代码在 gitHub 下:https://github.com/Clemens-Dautermann

【问题讨论】:

    标签: node.js angular express httprequest angular5


    【解决方案1】:

    您不想实际订阅您的方法。相反,您希望从 http 请求返回可观察的结果。

    如果要记录调试以查看结果,可以在可观察链上链接do 操作。

    如果你想对结果进行处理以转换它,你可以在你的 observable 链上使用map 操作符。

    如果您想处理由于无法与服务器通信而导致的错误,您可以使用catch 运算符并返回适当的结果或进行一些其他处理。

    getApacheRunning(): Observable<string> {
        return this.http.get('http://localhost:3000/ison')
            .do(res => console.log('apacheRunning ', res))
            .map(res => (res === 'true').toString())
            .catch(err => {
                console.log('Failed to determine if Apache is running', err);
                return Observable.of('false');
            });
    }
    

    【讨论】:

      【解决方案2】:

      您正在尝试获取 Async 请求,那么您需要在响应回调中捕获响应值看看这个例子:

      this.repository().subscribe(result =>{
         this.apacheRunning = result;
      });
      
      repository(){
          return this._http.get("http://localhost:3000/ison")
          .map(res => { 
              return res.json().map(item => { 
                 return item;
           });
         });
      }
      

      【讨论】:

        【解决方案3】:

        您需要在订阅循环中编写apacheRunning 条件。

        修改你的代码如下:

        getApacheRunning(): Observable<String>{
        
          this.apacheRunning = this.http.get("http://localhost:3000/ison").subscribe(result => {
            this.apacheRunning = result
            if(this.apacheRunning == "true"){
             console.log(this.apacheRunning + "DEBUG2");
             return of("true");
            }else{
              console.log(this.apacheRunning + "DEBUG1");
              return of("false")
            }
            console.log(result);
          },(err) => console.log(err), () => console.log("done"));
        }
        

        【讨论】:

          猜你喜欢
          • 2017-10-24
          • 1970-01-01
          • 1970-01-01
          • 2021-06-04
          • 1970-01-01
          • 2016-11-17
          • 1970-01-01
          • 2019-08-05
          • 2018-08-26
          相关资源
          最近更新 更多