Angular 4 - HttpClient无法隐藏状态代码错误消息

时间:2017-11-21 23:37:24

标签: angular

我将post auth请求发送到服务器。我为请求添加了错误hanlder,但我得到下面的控制台错误:

  

POST http://localhost:7777/auth 401(未经授权)

http://prntscr.com/hdjm6h

我从服务器发送401代码进行测试,现在我不知道已删除此消息。

import {HttpClient} from "@angular/common/http";
import {WebStorage} from "../singleton/web-storage";
import {environment} from "../../environments/environment";
import * as $ from "jquery/dist/jquery.slim";
import {Injectable} from "@angular/core";
import {Observable} from "rxjs/Observable";
import * as jwtDecode from 'jwt-decode';
import {RequestHandler} from "../handler/request.handler";

@Injectable()
export class Auth {

    constructor(private httpClient: HttpClient,
                private requestHandler: RequestHandler) {

    }

    /**
     * Check is user authorized
     *
     * @returns {Observable<Response>}
     */
    isAuthorized(): Observable<Response> {
        return new Observable((observer) => {
            let formData: Object = $.param({
                transferData: {
                    jwt: WebStorage.ssRetrieve('jwt')
                }
            });

            this.httpClient.post<Object>(environment.getUrl('/auth'), formData, {
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                }
            })
                .subscribe(
                    (response: Response) => {
                        observer.next(response);
                    },
                    error => {}// For this example, error handler is empty, just for hide most console errors
                );
        });
    }
}

任何建议!

1 个答案:

答案 0 :(得分:1)

您可以使用Observable的catch属性:

this.httpClient.post(your_url).catch((ex,caught) => {
 console.log('An exception has been caught!');
 return Observable.empty();
})

这里不是返回空的Observable,而是抛出错误,但这是你想要避免的。所以返回空的Observable可以解决你的问题。