首页 > 解决方案 > 如何将component.ts中的变量发送到service.ts以进行身份​​验证Angular

问题描述

我正在尝试从后端获取 auth_token 并在服务类中使用它。LoginComponent 成功发送用户凭据并接收 auth_token(通过 console.log 验证)。但我不知道如何使用组件中的 auth_token 变量到服务类中将其放入 HttpHeaders。

我有一个基本的登录 html。我的 login.component.ts 看起来像这样:

import { LoginService } from './../../service/login.service';
import { Router } from '@angular/router';
import { Login } from './../../model/login';
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {

  login: Login;

  constructor(private service: LoginService,
    private router: Router) { }

  ngOnInit(): void {
    this.login = new Login();
  }

  sendLoginCredentials(){
    this.service.authorizeUser(this.login)
    .subscribe((data)=>{
      this.login.auth_token = data.auth_token;
      console.log(this.login.auth_token);
      this.router.navigate(['/home']);
    })
  }

}

页面重定向到主页,我得到一个 auth_token 回来。我已经通过 Postman 和 console.log() 验证了这一点。现在我需要在不同的服务类中使用 Angular HttpHeaders 中的这个 auth_token。这是我的 department.service.ts 请求部门列表:

import { Login } from './../model/login';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { Department } from '../model/department';
import 'rxjs/add/operator/map';

const URL = 'http://127.0.0.1:8000/api/';

@Injectable({
  providedIn: 'root',
})
export class DepartmentService {
  login: Login = new Login();

  httpHeaders = new HttpHeaders({
    'content-type': 'application/json',
    // Authorization: 'token 856f5464e0508620d4cb90d546817e201419a70e',
    Authorization: 'token ' + this.login.auth_token,
  });

  constructor(private http: HttpClient) {}

  getAllDepartments(): Observable<Department[]> {
    return this.http
      .get(URL + 'department-list/', { headers: this.httpHeaders })
      .map((resp) => resp as Department[]);
  }
}

如果我使用硬编码值(在注释中),该应用程序可以工作,但它在请求标头中给了我“未定义的令牌”。我在 Angular 方面没有太多经验,所以我被困在这里。谢谢!!

标签: angular

解决方案


您需要使用会话而不是类来存储“auth_token”

sessionStorage.setItem("AuthToken", JSON.stringify(data.auth_token));

并且每当您使用时,只需从会话中获取并像这样使用它:

let authValue = sessionStorage.getItem("AuthToken");

httpHeaders = new HttpHeaders({
    'content-type': 'application/json',
    Authorization: 'token ' + authValue,
});

推荐阅读