繁体   English   中英

如何将 component.ts 中的变量发送到 service.ts 进行身份验证 Angular

[英]How to send variable in component.ts to service.ts for authentication 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));

每当您使用 just get from session 并使用它时:

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

httpHeaders = new HttpHeaders({
    'content-type': 'application/json',
    Authorization: 'token ' + authValue,
});
you need to interceptor 
by interceptor you can set token in httpHeader

例如:

从“@angular/core”导入 {Injectable}; 从“@angular/common/http”导入 {HttpRequest, HttpHandler, HttpEvent, HttpInterceptor}; 从 'rxjs' 导入 {Observable}; 从“@core/authentication”导入{AuthService};

@Injectable() 导出类 JwtInterceptor 实现 HttpInterceptor {

 constructor(private authService: AuthService) { } intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { const token = this.authService.getToken() ; if (token !== '') { const authReq = request.clone({ setHeaders: { Authorization: `Bearer ${token}` } }); return next.handle(authReq); } else { return next.handle(request); } } }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM