【问题标题】:How to add error handling in angular 8 using snackbar without using centralized error handling如何在不使用集中式错误处理的情况下使用小吃吧在 Angular 8 中添加错误处理
【发布时间】:2021-02-21 02:23:45
【问题描述】:

我在 client.add.component.ts 中有这段代码,想对重复条目进行错误处理。我目前在控制台中收到 503 错误。

this.clientsSvc.createClient(client).subscribe(x => this.router.navigate(['../'], {relativeTo: this.route}));

如何在上面的代码中加入下面这行代码?

this.snackBar.open(`Duplicate Client Name`, null, {duration: 3000});

【问题讨论】:

    标签: angular error-handling snackbar


    【解决方案1】:

    我相信您只想在 createClient 的当前请求失败时才显示/处理错误

    在这种情况下检查错误回调中的状态码。

    this.clientsSvc.createClient(client)
    .subscribe(
       x => this.router.navigate(['../'], {relativeTo: this.route}),
       error => {
         if(error.status === 503) {
           this.snackBar.open(`Duplicate Client Name`, null, {duration: 3000});
         }
    
       }
    );
    

    【讨论】:

    • 我在 client.service.ts 文件中有以下代码。 createClient(post: Partial) { return this.http.post(this.api_url, post).pipe( tap(_ => this._updateClients.next(null)) ); } 如何改变这个?
    • 我认为你在错误回调中总是有完整的响应,不是吗?我认为“观察”参数只适用于“成功”回调...
    • @smiti 您不必更改client.service.ts 中的代码,使用我在答案中提到的代码更改this.clientsSvc.createClient(client).subscribe(x => this.router.navigate(['../'], {relativeTo: this.route}));
    • @Random 我的错。你是对的,更新了答案。感谢您的提醒:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-25
    • 1970-01-01
    相关资源
    最近更新 更多