【问题标题】:Angular 2 - How to catch 401 error when calling web serviceAngular 2 - 调用 Web 服务时如何捕获 401 错误
【发布时间】:2017-02-21 18:21:32
【问题描述】:

我通过发送用户的用户名和密码来调用网络服务。如果提供了错误的用户名和密码,我会收到 401 UNAUTHORIZED 错误。我希望能够在 401 发生时捕捉到,以便在屏幕上输出错误消息。

这里是调用服务的代码:

return this.client.get<User>(this.BASEURL + 'api/id', new User(), null, encodedString)
        .map(result => {
            // If authorized, store the relevant information
            if (result) {
                result = new User().deserialize(result);
            }
            this.user.next(result);
            return result;
        }, this)
        .catch(this.handleError);

我试图在整个过程中使用 try catch,但它没有做任何事情(我猜是因为异步)。我还尝试了一个 console.log(result);在 if(result) 之后,但由于 401 错误,我从未访问过 .map。我不确定如何解决这个问题。谢谢!

【问题讨论】:

  • this.handleError 必须处理它。

标签: javascript angular try-catch


【解决方案1】:

你必须定义 handleError 方法。看看例子here

【讨论】:

    猜你喜欢
    • 2017-06-10
    • 2015-11-11
    • 1970-01-01
    • 2011-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-15
    • 2012-06-29
    相关资源
    最近更新 更多