Angular登录组件输入的API Key如何传递到Auth服务并更新服务内的APIkey变量
Angular登录组件输入的API Key如何传递到Auth服务并更新服务内的APIkey变量
我来帮你解决这个问题,核心思路是让Auth服务能够接收组件传递的API Key,并且动态生成请求URL(避免URL在初始化后固定不变)。下面是具体的修改步骤:
第一步:修改AuthService,支持动态设置API Key和生成请求URL
原来的APIkey是固定值,而且signUpURL和signInURL在类初始化时就确定了,这样即使后续更新API Key,URL也不会同步变化。我们需要调整成动态模式:
import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http' @Injectable({ providedIn: 'root' }) export class AuthService { private _apiKey: string = ''; // 改为私有变量,初始为空 isLoggedIn = false; constructor(private http: HttpClient) { } // 新增:设置API Key的方法,供组件调用 setApiKey(apiKey: string) { this._apiKey = apiKey; } // 私有方法:动态生成带API Key的请求URL private getAuthEndpointUrl(endpoint: string): string { return `https://gorest.co.in/public/v2/${endpoint}?access-token=${this._apiKey}`; } isAuthenticated(){ return this.isLoggedIn; } signUp(email: string, name: string, gender: string, status: string){ // 动态生成注册URL const signUpUrl = this.getAuthEndpointUrl('users'); return this.http.post(signUpUrl, {email, name, gender, status, returnSecureToken: true}); } // 调整登录逻辑:gorest的API是用access-token授权,所以登录其实是验证token有效性 signIn(){ const signInUrl = this.getAuthEndpointUrl('users'); // 发送GET请求验证token是否有效(因为POST /users是创建用户,不是登录) return this.http.get(signInUrl); } }
第二步:修改SigninComponent,传递API Key并触发登录验证
在组件的提交方法中,先把用户输入的API Key传给AuthService,再调用登录方法验证token是否有效:
import { Component } from '@angular/core'; import { NgForm } from '@angular/forms'; import { AuthService } from '../auth/auth.service'; @Component({ selector: 'app-signin', templateUrl: './signin.component.html', styleUrls: ['./signin.component.css'] }) export class SigninComponent { constructor(private authService: AuthService){} onSubmit(accesstoken: string) { // 1. 将用户输入的API Key设置到Auth服务中 this.authService.setApiKey(accesstoken); // 2. 调用登录方法验证token有效性 this.authService.signIn().subscribe({ next: (response) => { // 请求成功=token有效,标记登录状态 this.authService.isLoggedIn = true; console.log('登录成功,API Key有效', response); // 这里可以添加路由跳转,比如跳转到首页 }, error: (error) => { // 请求失败=token无效,提示用户 this.authService.isLoggedIn = false; console.error('登录失败:无效的API Key', error); // 可以在这里显示错误提示给用户,比如用MatSnackBar } }); } }
额外说明:关于gorest API的逻辑
你原来的signIn方法用了POST请求到/users接口,但实际上gorest的POST /users是创建新用户(注册),而验证access-token是否有效的方式应该是发送一个授权的GET请求(比如获取用户列表),如果请求成功,说明token是有效的。所以我调整了signIn方法的逻辑,你可以根据实际需求再调整。
备注:内容来源于stack exchange,提问作者user19761134
相关产品推荐
相关产品推荐

