在我的服务中,我想描述在未经授权的情况下重定向用户时的行为.
export class MessagesService { constructor (private http: Http) {} private _usersUrl = '/users.json'; // URL to web api getUsers() { return this.http.get(this._usersUrl) .map(res => <User[]> res.json().data) .catch(this.handleError); } private handleError (error: Response) { if (error.status == 401) { // How do I tell Angular to navigate LoginComponent from here? } else { return Observable.throw(error.json().error || 'Server error'); } } }
我的问题是:
>甚至可能吗?
>这是一个好习惯吗?
>如果是,我该怎么做?
>如果不是,我怎么能这样做?
我的方法是创建自己的请求服务,并有一个拦截器函数,它包含处理401和403等的实际请求.
原文链接:https://www.f2er.com/angularjs/240430.html如果您想查看它,请将其包含在下方.
import {Injectable} from "@angular/core" import {Subscription,Observable} from "rxjs" import {TokenModel} from "../../models/token.model" import {TokenService} from "../authentication/token.service" import {Http,Headers,URLSearchParams,RequestOptions,Request,RequestMethod} from "@angular/http" import {Router} from "@angular/router" @Injectable() export class RequestService { private baseUrl: string; private subscription: Subscription; private token: TokenModel; constructor(public tokenService: TokenService,public http: Http,public router: Router) { this.baseUrl = `${process.env.API_URL}/example`; this.subscription = this.tokenService.token$.subscribe(token => this.token = token); } get(path: string,params?: Object,withCredentials?: boolean): Observable<any> { this.checkAuthorised(); const url: string = this.baseUrl + path; const headers: Headers = new Headers({ 'Accept': 'application/json' }); const searchParams = new URLSearchParams(`user_session=${this.token.token}`); for (let param in params) searchParams.set(param,params[param]); const options: RequestOptions = new RequestOptions({ url: url,method: RequestMethod.Get,headers: headers,search: searchParams,withCredentials: withCredentials }); const request = new Request(options); return this.makeRequest(request); } post(path: string,body?: Object,useDataProperty?: boolean,withCredentials?: boolean): Observable<any> { this.checkAuthorised(); const url: string = this.baseUrl + path; const headers: Headers = new Headers({ 'Accept': 'application/json','Content-Type': 'application/json',}); const data = JSON.stringify(useDataProperty ? {data: body} : body); const searchParams = new URLSearchParams(`user_session=${this.token.token}`); for (let param in params) searchParams.set(param,method: RequestMethod.Post,body: data,withCredentials: withCredentials }); const request = new Request(options); return this.makeRequest(request); } makeRequest(request: Request) { return this.intercept(this.http.request(request).map(res => res.json())); } intercept(observable: Observable<any>) { return observable.catch(err => { if (err.status === 401) { return this.unauthorised(); } else if (err.status === 403) { return this.forbidden(); } else { return Observable.throw(err); } }); } unauthorised(): Observable<any> { this.tokenService.clear(); this.router.navigate(['/login']); return Observable.empty(); } forbidden(): Observable<any> { this.router.navigate(['/']); return Observable.empty(); } checkAuthorised(): void { if (!this.token.token.length) { this.router.navigate(['login']); } } }