代码之家  ›  专栏  ›  技术社区  ›  expenguin

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

  •  1
  • expenguin  · 技术社区  · 6 年前

    我有一个组件,它会发出一个HTTP请求来获取一些数据。响应可能包括来自请求的错误,我希望使用单独的错误组件/服务/视图在应用程序中显示这些错误。

    我把我的部件装在 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)
    ...
    

    错误.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
        }
    ...
    

    错误.component.html

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

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

    2 回复  |  直到 6 年前
        1
  •  2
  •   nircraft    6 年前

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

    我宁愿用 BehaviorSubject .

    例如,错误服务将错误定义为行为主题,并在错误组件中订阅它。一旦出现新的错误,您将在组件中得到该错误。

    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将始终显示应用程序中看到的最新错误。

        2
  •  1
  •   Nuno Sousa    6 年前

    另一个答案中的可观察模式是 最好的 以及更具角度的主题方式。

    但是,只需在服务和组件之间共享一个错误对象就可以了(服务在这里像一个全局包装器一样工作,但是根据Angular团队的说法,这也是允许的)。

    错误.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
        }
    

    错误.组件.ts

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

    每当某个组件将某个内容推入ErrorService时,将通知该错误组件更改,因为它正在监视的某个变量已更改。

    推荐文章