【问题标题】:Insert token into header as http call将令牌作为 http 调用插入标头
【发布时间】:2018-04-26 22:45:23
【问题描述】:

我有代码:

const parameters = 'Account/GetDoctorDetails?userId=' + 63;
this.http.get(`${webserviceUrlLocalHost}` + parameters)
.subscribe(response => {
  console.log('response.json()');
  console.log(response.json());

我想在这个调用中插入一个令牌到 GET webapi 调用中,所以我将代码更改为:

const headers = new Headers({ 'Authorization': `Bearer ` + token });
const options2 = new RequestOptions({ headers: headers });
return this.http.get('http://localhost:55803/Account/GetDoctorDetails?userId=63', options2)
    .subscribe( response => console.log(response.json())); */

但是函数永远不会被调用;知道为什么它不起作用吗?

【问题讨论】:

    标签: angular token


    【解决方案1】:

    尝试使用new HttpHeaders 而不是new RequestOptionsdeprecated), 来自documentation

    添加标题,如:

    const httpOptions = {
      headers: new HttpHeaders({
        'Content-Type':  'application/json',
        'Authorization': 'my-auth-token'
      })
    };
    

    所以你的options2 应该是:

    const options2 = {
      headers: new HttpHeaders({
        'Content-Type':  'application/json',
        'Authorization': `Bearer ` + token
      })
    };
    

    【讨论】:

    • 嗨 Taki,我在更改您的代码时遇到错误:Argument of type '{ headers: HttpHeaders; }' 不可分配给“RequestOptionsArgs”类型的参数。属性“标题”的类型不兼容。类型“HttpHeaders”不可分配给类型“Headers”。 “HttpHeaders”类型中缺少属性“forEach”。
    【解决方案2】:
    let headers = new HttpHeaders()
                .append('Content-Type', 'application/json')
                .append('Authorization',`Bearer ` + token );
    let params = new HttpParams()
                    .append('userId', '63')
    
    return new Observable<any>(observer => {
                    this.http.get('your-Rest-API-URL', { headers ,params}).subscribe((response) => {
                        observer.next(response);
                        observer.complete();
                    }, (error) => { });
                });
    

    【讨论】:

    • 嗨,我不明白为什么有这么多方法可以做同样的事情?
    • 不是另一种方式,只是试图通过删除硬编码部分来简化代码,例如您的案例中的 userId。
    猜你喜欢
    • 2016-11-27
    • 1970-01-01
    • 1970-01-01
    • 2013-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-04
    • 2019-11-29
    相关资源
    最近更新 更多