标头未在存储承诺中设置

时间:2017-12-05 13:10:08

标签: angular typescript ionic2

我正在尝试为我的api调用添加标头,但是,我需要获取身份验证令牌并将其设置为标头。但是,当我尝试运行波纹管代码时,它没有设置它,只设置内容类型。

import {HttpClient, HttpHeaders} from '@angular/common/http';
import {Component, Injectable} from '@angular/core';
import { Storage } from "@ionic/storage";
import 'rxjs/add/operator/map';

@Injectable()
@Component({
  providers: [HttpClient]
})
export class DataProvider {
  public token:string;

constructor(public http: HttpClient, public storage: Storage) {}

getsomething(){

 let headers = new HttpHeaders();
 headers = headers.set('Content-Type', 'application/json');
 this.storage.get('token').then((val) => {
   this.token = val;
   console.log(this.token);
   headers = headers.set('AuthToken', this.token);
 });

 console.log(headers);

 return this.http.get('http://localhost:54951/getfarms', {
   headers: headers
 });

}

3 个答案:

答案 0 :(得分:1)

您可以尝试使用Observable.flatMap,如下例

import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Storage } from "@ionic/storage";
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/mergeMap';

@Injectable()
export class DataProvider {
  constructor(public http: HttpClient, public storage: Storage) { }

  getsomething() {
    return Observable.fromPromise(this.storage.get('token')).flatMap((token) => {
      console.log(token);
      let headers = new HttpHeaders();
      headers = headers.set('Content-Type', 'application/json');
      headers = headers.set('AuthToken', token);
      console.log(headers);

      return this.http.get('http://localhost:54951/getfarms', {
        headers: headers
      });
    });
  }
}

答案 1 :(得分:0)

header.set()函数不返回标头实例,请执行以下操作

headers = header.set('AuthToken', this.token); //change the line
headers.set('AuthToken', this.token); //do not reassign the headers object

答案 2 :(得分:0)

在调用this.storage.get('token').then后,您无法使用您在then中设置的值。承诺不会立即执行处理程序,因为它是异步操作。

getsomething() {

    let headers = new HttpHeaders();
    headers = headers.set('Content-Type', 'application/json');
    return this.storage.get('token').then((val) => {
        this.token = val;
        console.log(this.token);
        headers = headers.set('AuthToken', this.token);


        console.log(headers);

        return this.http.get('http://localhost:54951/getfarms', {
            headers: headers
        });
    });
}

或使用async / await

async getsomethingAsync() {

    let headers = new HttpHeaders();
    headers = headers.set('Content-Type', 'application/json');
    let val = await this.storage.get('token')
    this.token = val;
    console.log(this.token);
    headers = headers.set('AuthToken', this.token);


    console.log(headers);

    return this.http.get('http://localhost:54951/getfarms', {
        headers: headers
    });
}