如何使用Angular httpClient拦截器?

时间:2018-01-16 18:48:20

标签: angular http-headers cors angular-services

我从其他域调用API所以我面临CORS问题所以我厌倦了使用Angular文档实现Angular httpClient拦截器,它抛出错误/service/getHistoricEvents: Response for preflight is invalid (redirect)知道下面的代码中缺少什么以及如何解决这个问题?

token.interceptor.ts

import { Injectable } from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor
} from '@angular/common/http';
import { AuthService } from './auth.service';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class TokenInterceptor implements HttpInterceptor {
  constructor(public auth: AuthService) {}
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    request = request.clone({
      setHeaders: {
        Authorization: "Basic bTA5NDg1QGNvbGxhYYXR0LmNvbTpjYnVzTVNAMjAxNw=="
      }
    });
    return next.handle(request);
  }
}

app.module.ts

import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { TokenInterceptor } from './token.interceptor';
@NgModule({
  bootstrap: [AppComponent],
  imports: [...],
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: TokenInterceptor,
      multi: true
    }
  ]
})
export class AppModule {}

searc.component.ts

 constructor(private http: HttpClient) { }
     getSearch(searchObj:{}) {

        console.log("searchObj",searchObj)
        return this.http.post('http://service/getHistoricEvents',JSON.stringify(searchObj))
          //.map(res => res.json());
          .map(res => console.log(res));
      }

0 个答案:

没有答案