angular - 如何将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 方面没有太多经验,所以我被困在这里。谢谢!!
解决方案
您需要使用会话而不是类来存储“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,
});
推荐阅读
- excel - 如何遍历行数不同的每一行?
- c# - 如何从鼠标坐标中获得正确的像素位置?
- python - 碰撞检测在 pygame 中无法正常工作
- jmeter - 在 Load runner 中处理相关性并在 JMeter 中使用它们
- javascript - Javascript - 数组问题
- python - 如果任何其他列符合某些条件,如何在熊猫中删除整个组?
- python - KivyMD:更改 MDLabel 的 font_name
- kubernetes - 无法使用 NodePort 转发流量
- typescript - 如何在不省略类型注释的情况下为 TypeScript 中具有许多属性的对象提供类型安全?
- reactjs - React 原生网页分割点