【问题标题】:Angular Client Side Errors Log to ServerAngular 客户端错误记录到服务器
【发布时间】:2019-03-19 12:48:17
【问题描述】:

我想将客户端角度错误记录到服务器,所以我遵循thisthis stackoverflow 答案并实施了一项服务 这使得 http 呼叫服务器。目前logError 方法正在被命中,但未对服务器进行 http 调用。

export class AngularLoggerService {
constructor(private http: HttpClient) {}

logError(error: Error) {
   console.log(error.stack); // line is printed to console
   this.http.post('/angular/log', {
     message: error.stack
   });
 }
}

Stackblitz Link

【问题讨论】:

  • 您的服务中缺少基本网址,请检查

标签: angular


【解决方案1】:

this.http.post 返回一个 observable 除非你在 observable 中使用.subscribe 方法,服务器调用不会进行如下更改你的代码

export class AngularLoggerService {
constructor(private http: HttpClient) {}

    logError(error: Error) {
       console.log(error.stack); // line is printed to console
       this.http.post('/angular/log', {
         message: error.stack
       }).subscribe((res) => console.log(res));
     }
    }

【讨论】:

  • 啊,所以你很快就指出了错误,我的错我忘记了订阅它的基本步骤!
  • 好吧,我也遇到了同样的问题。所以现在我给你解决方案。生活就是停止犯同样的错误..
【解决方案2】:

您需要将post 方法中的baseUrl(服务器URL)和subscribe 传递给Observable,这样您就可以成功或不成功地获得有关错误日志的响应。这是一个解决方案。

service.ts

import { Injectable, isDevMode } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class AngularLoggerService {

  baseUrl = "https://yourserver.com"
  constructor(private http: HttpClient) {}

  logError(error: Error) {
    console.log(error.stack);
    this.http.post(this.baseUrl +'/angular/log', {
      message: error.stack
    }).subscribe( (response) => {
      console.log(response);
    });
  }
}

Here is Forked Stackblitz solution

希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-19
    • 2019-08-20
    • 2013-10-21
    • 1970-01-01
    • 2010-09-12
    • 1970-01-01
    • 2016-04-27
    相关资源
    最近更新 更多