使用多个组件时如何处理错误

How to handle errors when using multiple components

我有一个组件发出 http 请求以获取一些数据。响应可能包括来自请求的错误,我想使用单独的错误 component/service/view.

在我的应用程序中显示这些错误

我已将我的组件放置在我的 app.component.html 视图中,例如:

<div>
    <app-error *ngIf="// check if endpoint returned errors, if yes, show"></app-error>
    <app-endpoint></app-endpoint>
</div>

我不确定如何从端点组件(错误将进入我的应用程序的地方)获取数据到错误组件和视图中。

举例来说,这在逻辑上是我希望在 EndpointComponent 尝试获取数据时发生的情况:

endpoint.component.ts

export class EndpointComponent 
{
    constructor(private errorService: ErrorService){ }

    getData(){
        this.endpointService.get().subscribe(
            response => checkError(response) // check and push to my error component if it exists)
...

error.service.ts

export class ErrorService 
{
    public pushErrors(error: string) {

        // In here would be the code to push this error
        // to error.component.ts / error.component.html
    }
...

error.component.html

<div class="alert alert-danger">
    <ul *ngFor="let error of errors">
        <li>{{error}}</li>
    </ul>
</div>

我不确定如何使用在我的端点组件中发回的错误来填充我的错误视图。由于只有在我的其他组件响应中存在错误时才会填充此视图,所以我不确定我们如何告诉我们的应用程序用错误数据填充元素。

我想你想要的是在错误组件中订阅错误服务error

我更愿意使用 BehaviorSubject

例如,在 Error 服务中将错误定义为 behaviorSubject 并在 ErrorComponent 中订阅它。推送新错误后,您将在组件中收到错误。

private errorObj = null;
    public errorList: BehaviorSubject<any> = new BehaviorSubject<any>(this.errorObj);

    pushError(value: any) {
        this.errorList.next(value);
    }`

现在在组件中订阅errorBanner。例如:this.errorService.errorBanner.subscribe( err => {this.showError = true;})

现在在错误组件中 HTML。使用 showError 显示从 errorService 收到的错误。

请注意,在这种情况下,ErrorComponent 将始终显示应用中出现的最新错误。

另一个答案中的可观察模式可能是 最好的 和更多 angular 主题方法。

但是在服务和组件之间共享一个错误对象是完全没问题的(这里的服务就像一个全局包装器,但根据 angular 团队也是允许的)。

error.service.ts

export class ErrorService 
{
    public errorList;
    public pushErrors(errors: string[]) {

        //I refactored this for plural 
        this.errorList.push(...errors);
    }
    public clearErrors(){
       this.errorList.splice(0,this.errorList.length) // we remove like this so that there is no reassignment
    }

error.component.ts

public error;
constructor(private errorService: ErrorService){
    this.errors = errorService.errorList
}

每当某个组件将某些内容推送到 ErrorService 时,ErrorComponent 将收到更改通知,因为它正在监视的变量已更改