Angular中如何从Authorization头获取JWT并存储到LocalStorage?
Got it, let's get this sorted! When your backend sends back the JWT in the Authorization response header, you can access this header directly from the HttpResponse object in your subscribe handler. Here's the modified version of your saveStudentDetails method with the required logic:
saveStudentDetails(values) { const studentData = {}; studentData['id'] = values.id; studentData['password'] = values.password; this.crudService.loginstudent(studentData).subscribe( (result: HttpResponse<any>) => { // Get the Authorization header from the response const authHeader = result.headers.get('Authorization'); if (authHeader) { // Usually the header is in format "Bearer <token>", so extract just the token const jwtToken = authHeader.split(' ')[1]; // Store the token in localStorage localStorage.setItem('studentJwtToken', jwtToken); } this.toastr.success('You are logged in', 'Success !', { positionClass: 'toast-bottom-right' }); this.router.navigate(['/address']); }, err => { console.log('status code ->' + err.status); this.toastr.error('Please try again', 'Error !', { positionClass: 'toast-bottom-right' }); } ); }
Key Details:
- Access the Response Headers: The
resultparameter in the success callback is anHttpResponseobject, which has aheadersproperty. Useresult.headers.get('Authorization')to fetch the specific header value. - Extract the Token: Most APIs format the Authorization header as
Bearer <your-jwt-token>, so we split the string to get just the token part (index 1 of the split array). If your backend returns the token directly without theBearerprefix, you can skip this split step and storeauthHeaderdirectly. - Persist to LocalStorage:
localStorage.setItem('studentJwtToken', jwtToken)saves the token in the browser's local storage, making it accessible across different routes and sessions (until the user clears their browser data).
Bonus Tip for Future Use:
To automatically include this JWT in subsequent API requests, you can create an Angular HTTP interceptor that fetches the token from localStorage and adds it to the Authorization header of every outgoing request. This saves you from manually adding the token to each service call.
内容的提问来源于stack exchange,提问作者Dory
相关产品推荐
相关产品推荐

