2017-09-15 154 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; 
    } 
} 

可以在Angular4創建HttpInterceptor這樣和HttpFactory象下面這樣:

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

我使用localStorage的這個,如果你不要求刪除相應

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

呼叫像這個在app.module.ts裏面的提供者。

+0

請你能解釋一下代碼嗎? –

+0

InterceptedHttp類包含所有的CRUD操作函數,它們可以處理加載程序的自動顯示,在需要爲webapi傳遞標題中的authtoken時使用authToken,使用'environment.ts'中的操作名稱和基礎URL更新url。 你的組件可以簡單地導入http。 '從'@ angular/http'導入{Http};' 並使用像普通的http調用。 –