问题
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