2016-04-14 6 views
6

मेरी सेवा में, मैं किसी व्यवहार का वर्णन करना चाहता हूं जब अधिकृत नहीं होने पर उपयोगकर्ता को रीडायरेक्ट किया जा रहा है।कोणीय 2: अगर एपीआई एक त्रुटि देता है तो रीडायरेक्ट कैसे करें?

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'); 
     } 
    } 
} 

मेरे प्रश्न हैं:

  • यह भी संभव है?
  • क्या यह एक अच्छा अभ्यास है?
    • यदि हां, तो मैं इसे कैसे कर सकता हूं?
    • यदि नहीं, तो मैं और कैसे कर सकता हूं?
+0

देखें http://stackoverflow.com/questions/36599523/angular-2-route-to-404-page-when-route-param-is-invalid/36609006#36609006 –

+0

@ GünterZöchbauer यह नहीं करता है सेवा में राउटर का उपयोग करने के बारे में मेरे प्रश्न पर उत्तर दें – Viktor

+0

यकीन नहीं क्यों। यदि आप राउटर 'कंस्ट्रक्टर (निजी http: एचटीपी, निजी राउटर: राउटर) {}' इंजेक्ट करते हैं तो आप इसका उपयोग करने में सक्षम होना चाहिए। प्रश्न के नीचे लिंक भी देखें। –

उत्तर

9

मेरे दृष्टिकोण अपने ही अनुरोध सेवा बना सकते हैं और एक इंटरसेप्टर समारोह जो संभाल करने 401 और 403 आदि

यह शामिल है नीचे अगर आप इसे पर एक नजर है करना चाहते हैं वास्तविक अनुरोध लपेटता है करने के लिए था ।

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, params?: 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, params[param]); 

     const options: RequestOptions = new RequestOptions({ 
      url: url, 
      method: RequestMethod.Post, 
      headers: headers, 
      body: data, 
      search: searchParams, 
      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']); 
     } 
    } 


} 
+0

मुझे नहीं लगता कि एक लिंक पोस्ट करना एक अच्छा विचार है। आपका जिस्ट एक दिन हटाया जा सकता है। मुझे लगता है कि यहां अपना कोड पोस्ट करना बेहतर है। – Viktor

0

एक दिशा हम अपनी टीम पर इस आ गया है एक API ग्राहक वर्ग को लागू करने से है। यह एपीआई क्लाइंट मूल एचटीपी सेवा लपेटता है।

विचार यह है कि जब से Http सेवा observables पैदा करता है आप आसानी से अपने व्यवहार को जोड़ने ऑपरेटरों द्वारा मूल नमूदार Http सेवा द्वारा उत्पादित करने के लिए map, flatMap और catch ऑपरेटरों की तरह का विस्तार कर सकते है।

मुझे लगता है कि आपको यह समस्या आपके पास होने वाली समस्या को ठीक करने के लिए एक उपयोगी प्रारंभिक बिंदु मिलेगी।

import { ApiRequestOptions } from './api-request-options.service'; 
import { Http, Response, RequestOptions, ResponseContentType } from '@angular/http'; 

import 'rxjs/add/observable/zip'; 
import 'rxjs/add/operator/map'; 
import { Observable } from 'rxjs/Rx'; 
import { Injectable } from '@angular/core'; 
import { Router } from '@angular/router'; 

@Injectable() 
export class ApiClient { 
    // PLease note, the API request options service is a helper that we introduced 
    // to generate absolute URLs based on settings in the client. 
    // I did not include it here for brevity. 
    constructor(private router: Router, private http: Http, private requestOptions: ApiRequestOptions) { 

    } 

    get<TResponse>(path: string, queryStringParams?: any): Observable<TResponse> { 
     let self = this; 

     return Observable.zip(
      this.requestOptions.absoluteUrlFor(path, queryStringParams), 
      this.requestOptions.authorizedRequestOptions() 
     ).flatMap(requestOpts => { 
      let [url, options] = requestOpts; 
      return self.http.get(url, options); 
     }).catch(response => { 
      if (response.status === 401) { 
       self.router.navigate(['/login']); 
      } 

      return response; 
     }).map((response: Response) => <TResponse>response.json()); 
    } 

    post<TResponse>(path: string, body: any): Observable<TResponse> { 
     let self = this; 

     return Observable.zip(
      this.requestOptions.absoluteUrlFor(path), 
      this.requestOptions.authorizedRequestOptions() 
     ).flatMap(requestOpts => { 
      let [url, options] = requestOpts; 
      return self.http.post(url, body, options); 
     }).catch(response => { 
      if (response.status === 401) { 
       self.router.navigate(['/login']); 
      } 

      return response; 
     }).map((response: Response) => <TResponse>response.json()); 
    } 

    put<TResponse>(path: string, body: any): Observable<TResponse> { 
     let self = this; 

     return Observable.zip(
      this.requestOptions.absoluteUrlFor(path), 
      this.requestOptions.authorizedRequestOptions() 
     ).flatMap(requestOpts => { 
      let [url, options] = requestOpts; 
      return self.http.put(url, body, options); 
     }).catch(response => { 
      if (response.status === 401) { 
       self.router.navigate(['/login']); 
      } 

      return response; 
     }).map((response: Response) => { 
      if (response.status === 200) { 
       return <TResponse>response.json(); 
      } else { 
       return null; 
      } 
     }); 
    } 

    delete(path: string): Observable<Response> { 
     let self = this; 

     return Observable.zip(
      this.requestOptions.absoluteUrlFor(path), 
      this.requestOptions.authorizedRequestOptions() 
     ).flatMap(requestOpts => { 
      let [url, options] = requestOpts; 
      return self.http.delete(url, options); 
     }).catch(response => { 
      if (response.status === 401) { 
       self.router.navigate(['/login']); 
      } 

      return response; 
     }); 
    } 
} 
संबंधित मुद्दे