Angular客户端错误记录到服务器

时间:2019-03-19 12:48:18

标签: angular

我想将客户端角度错误记录到服务器,因此我遵循了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

Image

2 个答案:

答案 0 :(得分:2)

this.http.post返回一个可观察的对象,除非您在可观察对象中使用.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));
     }
    }

答案 1 :(得分:0)

您需要在post方法中传递baseUrl(服务器URL),还需要在subscribe中传递Observable到该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); }); } } ,这样您才能成功地获得有关错误日志的响应。这是一个解决方案。

service.ts

protocol Protocol {}

extension String : Protocol {}

class A<T:Protocol> {}

class B : A<String> {}

Here is Forked Stackblitz solution

希望这会有所帮助!