Angular 4使用HttpClient模块设置标题 [英] Angular 4 Setting Headers with HttpClient Module

查看:216
本文介绍了Angular 4使用HttpClient模块设置标题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

新的Angular和我正在一个项目,由于某些原因,我必须为服务器端授权设置标题,Im使用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

推荐答案

它是不可变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模块设置标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆