2017-09-15 16 views
-2

インターセプタ

import {Injectable} from '@angular/core'; 
import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest} from '@angular/http'; 

@Injectable() 
export class NoopInterceptor implements HttpInterceptor { 
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { 
    return next.handle(req); 
    } 
} 

エラー

ERROR in C:/Users/mypc/workspace/angularapp/src/app/app.module.ts (5,9): Module '"C:/Users/mypc/workspace/angularapp/node_modules/@angular/http/http"' has no exported member 'HTTP_INTERCEPTORS'. 

ERROR in C:/Users/mypc/workspace/angularapp/src/app/interceptors/401.interceptor.ts (2,9): Module '"C:/Users/mypc/workspace/angularapp/node_modules/@angular/http/http"' has no exported member 'HttpEvent'. 

ERROR in C:/Users/mypc/workspace/angularapp/src/app/interceptors/401.interceptor.ts (2,20): Module '"C:/Users/mypc/workspace/angularapp/node_modules/@angular/http/http"' has no exported member 'HttpInterceptor'. 

ERROR in C:/Users/mypc/workspace/angularapp/src/app/interceptors/401.interceptor.ts (2,37): Module '"C:/Users/mypc/workspace/angularapp/node_modules/@angular/http/http"' has no exported member 'HttpHandler'. 

ERROR in C:/Users/mypc/workspace/angularapp/src/app/interceptors/401.interceptor.ts (2,50): Module '"C:/Users/mypc/workspace/angularapp/node_modules/@angular/http/http"' has no exported member 'HttpRequest'. 

ERROR in C:/Users/mypc/workspace/angularapp/src/app/interceptors/401.interceptor.ts (6,56): Cannot find name 'Observable'. 

ERROR in C:/Users/mypc/workspace/angularapp/src/app/app.module.ts (5,9): Module '"C:/Users/mypc/workspace/angularapp/node_modules/@angular/http/http"' has no exported member 'HTTP_INTERCEPTORS'. 
+0

したがって、質問タイトルを参照してください。 –

答えて

0

正しいパッケージが@angular/common/httpです。ところで、私はそれが4.3.xバージョンでのみ利用可能だと思います。 @angular/httpは今後使用されなくなります。

+0

これは私が角の解決策を探していると述べた理由です。4.2.5 –

-1
import { Injectable } from "@angular/core"; 
import { ConnectionBackend, RequestOptions, Request, RequestOptionsArgs, Response, Http, Headers } from "@angular/http"; 
import { Observable } from "rxjs/Rx"; 
import { Router } from '@angular/router'; 
import { environment } from "../../../environments/environment"; 
import {LoaderService} from '../loader/loader.service'; 
import {LocalStorageService} from '../_services/localstorage.service'; 

@Injectable() 
export class InterceptedHttp extends Http { 
    router: Router; 
    loaderService:LoaderService; 
    constructor(backend: ConnectionBackend, defaultOptions: RequestOptions,private _router: Router, 
     private _loaderService:LoaderService,private _localStorageService:LocalStorageService) { 
     super(backend, defaultOptions); 
     this.router = _router; 
     this.loaderService=_loaderService; 
    }  
    get(url: string, options?: RequestOptionsArgs): Observable<Response> { 
     url = this.updateUrl(url); 
     return this.intercept(super.get(url, this.getRequestOptionArgs(options))); 
    } 

    post(url: string, body: string, options?: RequestOptionsArgs): Observable<Response> { 
     url = this.updateUrl(url); 
     let data=body;//url.endsWith('token')?body:JSON.stringify(body);//fr token url only 
     return this.intercept(super.post(url, data, this.getRequestOptionArgs(options))); 
    } 

    put(url: string, body: string, options?: RequestOptionsArgs): Observable<Response> { 
     url = this.updateUrl(url); 
     return this.intercept(super.put(url, body, this.getRequestOptionArgs(options))); 
    } 

    delete(url: string, options?: RequestOptionsArgs): Observable<Response> { 
     url = this.updateUrl(url); 
     return this.intercept(super.delete(url, this.getRequestOptionArgs(options))); 
    } 

    private updateUrl(req: string) { 
     this.showLoader(); 
     return environment.origin +'/'+ req; 
    } 

    private getRequestOptionArgs(options?: RequestOptionsArgs): RequestOptionsArgs { 
     if (options == null) { 
      options = new RequestOptions(); 
     } 
     if (options.headers == null) { 
      options.headers = new Headers(); 
     } 
     options.withCredentials=true; 
     options.headers.append('Content-Type', 'application/json'); 
     options.headers.append('Authorization', 'Bearer ' + this._localStorageService.getAuthToken()); 
     //options.headers.append('Content-Type', 'application/x-www-form-urlencoded'); 
     return options; 
    } 


    private onEnd(): void { 
     this.hideLoader(); 
    } 
    private showLoader(): void { 
     this.loaderService.show(); 
    } 
    private hideLoader(): void { 
     this.loaderService.hide(); 
    } 

    intercept(observable: Observable<Response>): Observable<Response> { 
     //return observable.map(response => response.json()) 
     return observable.catch((err, source) => { 
      if (err.status === 401) { 
       alert('You are not authorized to access the resource'); 
       //setTimeout(() => this.router.navigate(['/login']), 3000); 
       setTimeout(() => document.location.href='/login', 3000);     
       return Observable.empty(); 
      } 
      else if (err.status === 404) { 
       console.log(['http service',err]); 
       document.location.href='/not-found';     
       return Observable.empty(); 
      } 
      else { 
       console.log(['htto errir',err]); 
       err.errors=this.parseErrors(err); 
       return Observable.throw(err); 
      } 
     }).finally(() => { 
      this.onEnd(); 
     }); 
    } 

    parseErrors(response): Array<string> 
    { 
     let errors:Array<string>=new Array<string>(); 

     if (response) { 
      response=JSON.parse(response._body); 
      if (response.error_description) { 
       errors.push(response.error_description); 
      } 
      if (response.message) { 
       errors.push(response.message); 
      } 
      for (var key in response.modelState) { 
       for (var i = 0; i < response.modelState[key].length; i++) { 
        errors.push(response.modelState[key][i]); 
       } 
      } 
     } else { 
      errors.push('Server response null'); 
     } 
     return errors; 
    } 
} 

あなたはこれとHttpFactory以下のようなのようなAngular4でHttpInterceptorを作成することができます:あなたはそれに応じ

{ 
    provide: Http, 
    useFactory: httpFactory, 
    deps: [XHRBackend, RequestOptions,Router,LoaderService,LocalStorageService ] 
}, 

コールを削除する必要がない場合、私はこの中のlocalStorageを使用しています

import {XHRBackend, Http, RequestOptions} from "@angular/http"; 
import {Router} from "@angular/router"; 
import {InterceptedHttp} from "./http.interceptor"; 
import {LoaderService} from '../loader/loader.service'; 
import {LocalStorageService} from '../_services/localstorage.service'; 

export function httpFactory(xhrBackend: XHRBackend, requestOptions: RequestOptions,router:Router, 
    loaderService:LoaderService,localStorageService:LocalStorageService): Http { 
    return new InterceptedHttp(xhrBackend, requestOptions,router,loaderService,localStorageService); 
} 

プロバイダー内のapp.module.tsにあるように。

+0

コードを説明してください。 –

+0

InterceptedHttpクラスには、webapiのヘッダにauthtokenを渡す必要がある場合にauthTokenを使用し、アクション名でurlを更新し、 'environment.ts'からのベースURLを更新する必要がある場合に、authTokenを使用してローダの自動表示を処理できるCRUD操作関数がすべて含まれています あなたのコンポーネントを単にhttpをインポートすることができます。 '@ angle/http'から 'import {Http}; ' と一般的なhttp呼び出しのように使用します。 –

関連する問題