Angular Client Side Errors Log to Server

[亡魂溺海] 提交于 2021-02-10 05:04:33

问题


I want to log to client side angular errors to Server, so I followed this and this stackoverflow answers and implemented a service which makes a http call server. For now the logError method is getting hit but http call is not made to server.

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


回答1:


this.http.post returns an observable unless you use .subscribe method in the observable, the server call wont be made change your code as follows

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:


You need to pass the baseUrl (server URL) in your post method and also subscribe to that Observable so that you will get the response back about error log successfully or not. Here is a solution.

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

Hope this will help!



来源:https://stackoverflow.com/questions/55241453/angular-client-side-errors-log-to-server

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!