在Angular 2中,如果用户未使用路由器版本2.0.0-rc.1进行身份验证,我该如何重定向用户
我希望在我的路径存储的app.component中执行此操作。
我想在用户点击页面组件之前检测用户是否经过身份验证。 所以我可以将它们重定向到登录。
我尝试过 canActivate ,这似乎不适用于我的路由器版本。
我正在为这个版本的路由器寻找解决方案:“@ angular / router”:“2.0.0-rc.1”
OR
最新版路由器的解决方案。如果提供了一个,你可以告诉我如何使用git bash更新我的路由器版本。
这是我目前的代码:
export class AppComponent implements CanActivate {
authService: AuthService;
userService: UserService;
constructor(_authService: AuthService, _userService: UserService, private location: Location, private router: Router) {
this.authService = _authService;
this.userService = _userService;
}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable < boolean > | boolean {
//This doesnt get hit
console.log("here");
return true;
}
}
答案 0 :(得分:2)
使用Interceptor
:
import {bootstrap} from '@angular/platform-browser-dynamic';
import {provide} from '@angular/core';
import {HTTP_PROVIDERS, Http, Request, RequestOptionsArgs, Response, XHRBackend, RequestOptions, ConnectionBackend, Headers} from '@angular/http';
import {ROUTER_PROVIDERS, Router} from '@angular/router';
import {LocationStrategy, HashLocationStrategy} from '@angular/common';
import { Observable } from 'rxjs/Observable';
import * as _ from 'lodash'
import {MyApp} from './app/my-app';
class HttpInterceptor extends Http {
constructor(backend: ConnectionBackend, defaultOptions: RequestOptions, private _router: Router) {
super(backend, defaultOptions);
}
request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
return this.intercept(super.request(url, options));
}
get(url: string, options?: RequestOptionsArgs): Observable<Response> {
return this.intercept(super.get(url,options));
}
post(url: string, body: string, options?: RequestOptionsArgs): Observable<Response> {
return this.intercept(super.post(url, body, this.getRequestOptionArgs(options)));
}
put(url: string, body: string, options?: RequestOptionsArgs): Observable<Response> {
return this.intercept(super.put(url, body, this.getRequestOptionArgs(options)));
}
delete(url: string, options?: RequestOptionsArgs): Observable<Response> {
return this.intercept(super.delete(url, options));
}
getRequestOptionArgs(options?: RequestOptionsArgs) : RequestOptionsArgs {
if (options == null) {
options = new RequestOptions();
}
if (options.headers == null) {
options.headers = new Headers();
}
options.headers.append('Content-Type', 'application/json');
return options;
}
intercept(observable: Observable<Response>): Observable<Response> {
return observable.catch((err, source) => {
if (err.status == 401 && !_.endsWith(err.url, 'api/auth/login')) {
this._router.navigate(['/login']);
return Observable.empty();
} else {
return Observable.throw(err);
}
});
}
}
bootstrap(MyApp, [
HTTP_PROVIDERS,
ROUTER_PROVIDERS,
provide(LocationStrategy, { useClass: HashLocationStrategy }),
provide(Http, {
useFactory: (xhrBackend: XHRBackend, requestOptions: RequestOptions, router: Router) => new HttpInterceptor(xhrBackend, requestOptions, router),
deps: [XHRBackend, RequestOptions, Router]
})
])
.catch(err => console.error(err));
答案 1 :(得分:1)
您可以使用此
fetch
在app.module.ts中
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpErrorResponse } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { Router } from '@angular/router';
@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
constructor(private router: Router) {}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(req)
.pipe(
catchError(
(err: HttpErrorResponse) => {
if (this.router.url !== '/login' && err.status === 401) {
this.router.navigate(['/login']);
}
return throwError(err);
}
)
);
}
}