【问题标题】:Angular 2 Check Status code 200 and 400Angular 2 检查状态码 200 和 400
【发布时间】:2018-05-01 06:37:20
【问题描述】:

我正在尝试向我的服务器发送密码 -> 服务器检查密码是否正确 -> 发送状态码:200 成功或 401 错误。

现在我正在检查状态代码,但感觉应该有更好的方法,因为下面的代码感觉很笨重。

我基本上只是想检查这两个状态码。

getTokenFromServer(value: Authentication): Observable <Authentication>{
        const httpOptions = {
                    headers: new HttpHeaders({ 'Content-Type': 'application/json'})
                };

                return this.http.post(serverUrl, value, httpOptions).pipe(
                    tap((response: any) => {
                        if(response.status == "200"){
                            console.log("Success logging in: "+response.status+":"+response.token);
                            this.tokenService.setToken(response.token);                 
                        }else{
                            console.log("Error logging in: " +response.status);
                        }
                    }),
                    catchError(this.handleError('Authenticate password:'))
                    );

            }

【问题讨论】:

    标签: angular http http-status-code-404


    【解决方案1】:

    只有 2xx 状态代码会进入您的点击功能,因此不需要进行 if 检查。 401 状态代码将导致抛出错误,这将由 catchError 函数引起。您可以简化为:

    return this.http.post(serverUrl, value, httpOptions).pipe(
        tap((response: any) => {
            console.log("Success logging in: "+response.status+":"+response.token);
            this.tokenService.setToken(response.token);                 
        }),
        catchError(this.handleError('Authenticate password:'))
    );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-17
      • 1970-01-01
      • 2017-07-06
      • 1970-01-01
      • 1970-01-01
      • 2011-08-13
      • 2021-08-05
      • 1970-01-01
      相关资源
      最近更新 更多