简体   繁体   English

rxjs的角发布:捕获错误

[英]Angular post with rxjs: catch error

I created an authentication service in my angular app with the help of several tutorials. 我借助一些教程在我的角度应用程序中创建了身份验证服务。 The happy path is working fine, but I can't handle 401 errors etc. in this case my map function is not called. 幸福的路径工作正常,但我无法处理401错误等。在这种情况下,不会调用我的map函数。

Any ideas how to handle login errors? 任何想法如何处理登录错误?

login(username: string, password: string): Observable<boolean> {

        return this.http.post(environment.baseUrl + '/api/authenticate', JSON.stringify({ username: username, password: password }))
            .map((response: Response, error: any) => {

                console.log('mapping response...', response.status.toString());

                // login successful if there's a jwt token in the response
                const token = response.json() && response.json().token;
                if (token) {
                    // set token property
                    this.token = token;

                    // store username and jwt token in local storage to keep user logged in between page refreshes
                    localStorage.setItem('currentUser', JSON.stringify({ username: username, token: token }));

                    // return true to indicate successful login
                    return true;
                } else {
                    // return false to indicate failed login
                    return false;
                }
            });

    }

You could try adding a catch like this: 您可以尝试添加一个这样的捕获:

    return this.http.post(environment.baseUrl + '/api/authenticate', JSON.stringify({ username: username, password: password }))
        .map((response: Response) => {

            console.log('mapping response...', response.status.toString());

            // login successful if there's a jwt token in the response
            const token = response.json() && response.json().token;
            if (token) {
                // set token property
                this.token = token;

                // store username and jwt token in local storage to keep user logged in between page refreshes
                localStorage.setItem('currentUser', JSON.stringify({ username: username, token: token }));

                // return true to indicate successful login
                return true;
            } else {
                // return false to indicate failed login
                return false;
            }
        })
         .catch(this.handleError);


private handleError(error: Response): Observable<any> {
    // in a real world app, we may send the server to some remote logging infrastructure
    // instead of just logging it to the console
    console.error(error);
    return Observable.throw(error.json().error || 'Server error');
}

Or to return false, you could change this as follows: 或返回false,可以如下更改:

import 'rxjs/add/observable/of';

private handleError(error: Response): Observable<any> {
    // in a real world app, we may send the server to some remote logging infrastructure
    // instead of just logging it to the console
    console.error(error);
    return Observable.of(false);
}

You could try to: 您可以尝试:

app.config(['$httpProvider', function($httpProvider) {

    $httpProvider.interceptors.push(function($q) {

        return {

            'responseError': function(rejection){

                var defer = $q.defer();

                if(rejection.status == 401){
                    console.dir(rejection);
                }

                defer.reject(rejection);

                return defer.promise;

            }
        };
    });

    }]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM