まず、私はAngularの初心者だと言及しなければならず、私はサンプルコードに固執しています。Angular2でのRESTサービスの例外処理
ユーザー名とパスワードの入力を求める簡単なログインアプリケーションを作成しました。ログイン成功時にトークンを返すlogin RESTサービス(Javaで書かれたもの)を呼び出します。
ここにいくつかのコードがあります。
ログインコンポーネント:
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { AuthenticationService } from '../_services/index';
@Component({
moduleId: module.id,
templateUrl: 'login.component.html'
})
export class LoginComponent implements OnInit {
model: any = {};
error = '';
constructor(
private router: Router,
private authenticationService: AuthenticationService) { }
ngOnInit() {
// reset login status
this.authenticationService.logout();
}
login() {
this.authenticationService.login(this.model.username, this.model.password)
.subscribe(result => {
if (result === true) {
this.router.navigate(['/']);
} else {
this.error = 'Login failed!';
}
},
err => {
this.error = 'Login failed!';
});
}
}
認証サービス:
import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions, Response } from '@angular/http';
import { Observable } from 'rxjs';
import { CookieService } from 'angular2-cookie/core';
import { CookieOptionsArgs } from 'angular2-cookie/services/cookie-options-args.model';
import 'rxjs/add/operator/map';
@Injectable()
export class AuthenticationService {
public token: string;
constructor(private http: Http, private cookieService: CookieService) {
// set token if saved in cookie
this.token = cookieService.get('token');
}
login(username, password): Observable<boolean> {
return this.http.post('http://localhost:9081/MyApp/login?username=' + username + '&password=' + password, new RequestOptions({}))
.map((response: Response) => {
// login successful if there's a token in the response
let token = response.text();
if (token !== '-1') {
// set token
this.token = token;
// store token in cookie to keep user logged
let opts: CookieOptionsArgs = {
path: '/'
};
this.cookieService.put('token', token, opts);
// return true to indicate successful login
return true;
} else {
// return false to indicate failed login
return false;
}
});
}
logout(): void {
// clear token, remove cookie to log user out
this.token= null;
this.cookieService.remove('token');
}
}
すべてが期待どおりに動作します。ログインが成功すると、トークンが返され、 "home"ページにリダイレクトされます。それ以外の場合は、ログインページに「ログイン偽装」というメッセージが表示され、リダイレクトは行われません。私が気になるのは、なぜログインが失敗するのか正確にはわからないということです。ユーザー名が存在しないか、パスワードが間違っている可能性があるからです。 RESTサービスによってスローされた例外を処理する適切な方法は何ですか?私は、認証サービスが適切な場所だと仮定しますが、私はそれを行う方法を正確には分かりません。私は要求オブジェクトからいくつかの情報を抽出しようとしましたが、例外がスローされた場合にはリクエストのマッピングは行われません。
ありがとうございました!
をあなたは、キャッチパラメータの観測に関するエラーを取得して、次のされている場合ヘルプ:https://stackoverflow.com/questions/37472770/catch-is-not-working-for-http-get-angular2/37475643#37475643 – Nitin