在Angular HttpClient拦截器中调用另外的接口

目的:我需要在向服务器发出请求之前获取一个令牌以添加到请求标头。

1:拦截器:

import { Http, Headers, RequestOptions, URLSearchParams } from '@angular/http';
import { Injectable } from '@angular/core';
import { fromPromise } from 'rxjs/observable/fromPromise';
import {
  HttpEvent, HttpInterceptor, HttpHandler, HttpRequest,
} from '@angular/common/http'
import { Observable } from 'rxjs/Observable'
import { EnvService } from './env.service'
import { AuthService } from './auth.service';
import { switchMap } from 'rxjs/operators';

@Injectable()
export class GlobalInterceptor implements HttpInterceptor {
  constructor(public http: Http,  private  authService: AuthService,
      private env: EnvService) {}
  intercept(req: HttpRequest, next: HttpHandler):
    Observable> {
      const thirdIndex = req.url.indexOf('/', 10) // 獲取第三個斜杠的位置
      const fouthIndex = req.url.indexOf('/', (thirdIndex + 1)) // 獲取第四個斜杠的位置
      const projectName = req.url.substring(thirdIndex + 1, fouthIndex) // 截取第三個和第四個斜杠的中間的字符串作為項目名
      const projectUrl = req.url.substr(0, fouthIndex + 1) + 'login'; // 調取相應項目的login接口
      const username = this.env[(projectName + 'UserName')];
      const password = this.env[(projectName + 'Password')];

      const datas = {
        'account': username,
        'pswd': password
      };
      if ( req.url.endsWith('loginCAS/jobLogin') || req.url.includes('rpa_back') ) {
        return next.handle(req);
      }
      // console.log(req.headers.get('Authorization'));

      if (req.headers.get('Authorization') === null ||  !req.headers.get('Authorization').startsWith('Bearer')) {

        return fromPromise(this.authService.getAuth(projectUrl, datas))
        .pipe(switchMap(token => {
            //  const headers = req.headers
            //           .set('Authorization', 'Bearer ' + token)
            //           .append('Content-Type', application/json');
            //  const reqClone = req.clone({
            //    headers
            //   });
            return next.handle(req);
       }));
}
 }

2:获取令牌的service

	import { Http, Headers, RequestOptions, URLSearchParams } from '@angular/http';
import { Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';

@Injectable()
export class AuthService {
  constructor(private http: Http) { }
   getAuth (url, datas) {
    let Authorization = '';
    const headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' }); // 第一处区别
    const options = new RequestOptions({ headers: headers }); // 第二处区别
    const params = new URLSearchParams();
    params.append('account', datas['account'] );
    params.append('pswd', datas['pswd']);
    const body = params.toString();

    return   this.http.post(url, body, options).toPromise();
  }
}

参考:https://cloud.tencent.com/developer/ask/196153

你可能感兴趣的:(Angular)