Angular:使用与HttpClient等效的Http RequestOptions

时间:2018-05-30 14:04:37

标签: angular typescript angular-http angular-httpclient

我正在从 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 的等价物,并且整个处理都无法添加相同的标题。

建议??

4 个答案:

答案 0 :(得分:3)

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)

您还可以查看this question

答案 1 :(得分:0)

http客户端应该是:

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

答案 2 :(得分:0)

我之前通过在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/

我使用Firebase Auth为我的令牌做过这样的事情。 这是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请求设置授权令牌,这样您就不必在发出请求之前等待令牌。请记住,这对Firebase Auth非常具体,因为它是给我JWT令牌的。希望这可以有所帮助!

答案 3 :(得分:0)

根据https://angular.io/guide/deprecations SELECT AuthorizationId ,Name ,CONVERT(VARCHAR(85), [ownersid], 2) AS ownersid ,[ownerSidWhereDefined] ,[AuthorizationType] ,ISNULL(CONVERT(NVARCHAR(10), [ValidFrom]), '') AS [ValidFrom] ,ISNULL(CONVERT(NVARCHAR(10), [ValidTo]), '') AS [ValidTo] from Authorization public class AuthorizationsFmt { public string AuthorizationId; public string ownerSid; public byte[] ownerSidWhereDefined; public string Name; public string AuthorizationType; public string ValidFrom; public string ValidTo; } IEnumerable<AuthorizationsFmt> FileData = from l in File.ReadLines(file) let x = l.Split( '\t') select new AuthorizationsFmt() { AuthorizationId = x.ElementAt(0), Name = x.ElementAt(1), ownerSid = Encoding.UTF8.GetBytes(x.ElementAt(2)), ownerSidWhereDefined = x.ElementAt(3), AuthorizationType = x.ElementAt(4), ValidFrom = x.ElementAt(5), ValidTo = x.ElementAt(6) }; return FileData; 取代