角:使用HTTP的RequestOptions相当于与HttpClient的(Angular : U

2019-09-29 05:00发布

我正在从http迁移到HttpClient的我已经习惯了一些添加像下面我的http请求:

import { RequestOptions, Request, RequestMethod, Headers } from '@angular/http';


this.pass = btoa(cuid + ': ');
this.pass = "Basic " + this.pass;
this.header = new Headers();
this.header.set("Authorization", this.pass);
let options = new RequestOptions({
  headers: this.header
});

return this.http.post(myServiceUrl, {}, options)

现在迁移到HttpClient的时候,我已经试过这样:

import {HttpClient, HttpHeaders} from '@angular/common/http';

    const header = new HttpHeaders();
    const pass = 'Basic ' + btoa(cuid + ': ');
    header.set('Authorization', pass);
    const options =  ({
      headers: header
    });
    return this.httpClient.post(myServiceUrl, {}, options);

但你可以看到ivent找到RequestOptions相当于,整个治疗未能添加相同的标题。

建议?

Answer 1:

HttpClient.post方法具有以下特征:

post(url: string, body: any | null, options: OptionsType)

OptionsType是以下(相当于RequestOptions

{
  headers?: HttpHeaders | { [header: string]: string | string[] };
  observe?: "body";
  params?: HttpParams | { [param: string]: string | string[] };
  reportProgress?: boolean;
  responseType: "arraybuffer";
  withCredentials?: boolean;
};

从那里,你可以指定你头或者参数,可以这样:

const options = {
  headers: new HttpHeaders().append('key', 'value'),
  params: new HttpParams().append('key', 'value')
}


this.httpClient.post(url, {}, options)

你也可以去看一下这个问题



Answer 2:

HTTP客户端等效的应该是:

const headers = new HttpParams().set('Authorization', pass);
return this.httpClient.post(myServiceUrl, {}, {headers: headers});


Answer 3:

我已经在我的服务作出方法做过getHeaders(token)

  getHeaders(token) {
    return new HttpHeaders().set('Authorization', `Bearer ${token}`);
  }

提出请求然后,当只是追加这像这样的要求:

this.http.post(url, body, this.getHeaders(token));

也有HttpInterceptor考虑这样做可以请求自动执行此,这里就是一个这样的文章: https://www.intertech.com/Blog/angular-4-tutorial-handling-refresh-token-with-new- httpinterceptor /

我这样做使用火力地堡验证了我的令牌这样。 这里是token.interceptor.ts文件:

@Injectable()
export class TokenInterceptor implements HttpInterceptor {

  afAuth: any;

  constructor(
    private inj: Injector
  ) { }

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    this.afAuth = this.inj.get(AngularFireAuth);

    return this.getToken().pipe(
      switchMap(token => {
        request = request.clone({
          setHeaders: {
            Authorization: `Bearer ${token}`
          }
        });

        return next.handle(request);
      })
    );
  }

  getToken() {
    return Observable.fromPromise(this.afAuth.auth.currentUser.getIdToken());
  }
}

然后,你需要提供给你的顶级app.module像这样:

{ provide: HTTP_INTERCEPTORS, useClass: TokenInterceptor, multi: true }

这里做的事情在这里设置授权令牌,所以您不必发出请求之前等待的令牌被自动处理每一个HTTP请求。 请记住,这是非常具体的火力地堡验证因为这就是是给我的JWT令牌。 希望这能有所帮助!



文章来源: Angular : Using the equivalent of RequestOptions of Http with HttpClient