我正在尝试将标头添加到我的API调用中,但是,我需要获取auth令牌并将其设置为标题。但是,当我尝试运行波纹管代码时,它不会设置它,仅设置内容类型。
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
});
}
您可以尝试使用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
});
});
}
}
header.set.set()函数不返回标头实例,因此请执行以下
headers = header.set('AuthToken', this.token); //change the line
headers.set('AuthToken', this.token); //do not reassign the headers object
您无法在调用then
后立即使用this.storage.get('token').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 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
});
}