问题描述
我是 Angular 的新手,我正在开发一个项目,由于某些原因我必须为服务器端授权设置标头,我使用 Angular 4 和从@angular/common/http"导入的 HttpClient 模块
im new with Angular and i'm working on a project that for some reasons i have to set headers for server side authorization, Im using Angular 4 and the HttpClient Module imported from '@angular/common/http'
这是我的 AuthService 类
This is my AuthService Class
import { Injectable } from '@angular/core';
import { User } from '../../models/user';
import { HttpClient, HttpHeaders, HttpRequest } from
'@angular/common/http';
import { Observable } from 'rxjs';
import { Globals } from '../../utils/global';
import { Converters } from '../../utils/converters';
@Injectable()
export class AuthService {
getUserByToken(token: string): any {
let headers = new HttpHeaders();
headers.append('Content-Type', 'application/json');
headers.append('authorization', 'Bearer ' + token);
console.log(headers);
return new Promise((resolve, reject) => {
this.http.get(this.global.urls['info'], { headers: headers }).subscribe((data) => {
if (data != null) {
this.converter.userJsonToObject(data).then((data: User) => {
this.setCurrentUser(data);
this.persistToken(data.token);
resolve(data);
});
} else {
reject('This user is not defined');
}
}, (err) => {
reject(err);
});
});
}
当我运行我的项目并调用 getUserByToken(token) 函数时,服务器控制台告诉我没有发送任何令牌.端点与 ARC 完美配合,因此问题出在客户端.有没有人可以帮我解决这个问题.:D
When i run my project and i call getUserByToken(token) function, the server console told me that no token was send.The endpoint is working perfect with ARC so the issue is on the client side.does anyone can help me to resolve this issue problem.:D
推荐答案
它是 immutable Map
类型,所以如果你分配一个新值,它将重新初始化对象,所以你应该这样做
It is of type immutable Map
so if you assign a new value it will reinitialize the object so you should be doing as
let headers = new HttpHeaders().set('Content-Type', 'application/json')
.set('authorization', 'Bearer ' + token);
或
let headers = new HttpHeaders().set('Content-Type', 'application/json');
headers = headers.set('authorization', 'Bearer ' + token);
这篇关于Angular 4 使用 HttpClient 模块设置标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!