You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular中SyntaxError: Unexpected token错误修复求助

错误原因与修复方案

错误根源

报错是因为LocalStorageService.getItem尝试将JWT token字符串直接用JSON.parse解析,但JWT本身是Base64编码的字符串,并非JSON格式,导致解析失败。同时可能存在token存储方式不规范的问题。


1. 修复LocalStorageService的getItem方法

增加空值校验和异常捕获,兼容JSON和普通字符串两种存储场景:

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class LocalStorageService {

  constructor() { }

  setItem(key:string, value:any){
    let json = JSON.stringify(value);
    localStorage.setItem(key, json);
  }

  getItem(key:string){
    let json = localStorage.getItem(key);
    if (!json) return null;
    try {
      return JSON.parse(json);
    } catch (error) {
      // 解析失败时直接返回原始字符串(比如JWT token)
      return json;
    }
  }

  isSaved(key: string) {
    return !!localStorage.getItem(key);
  }

  remove(key: string) {
    localStorage.removeItem(key);
  }

  removeAll() {
    localStorage.clear();
  }
}

2. 规范Token存储逻辑

确保登录时使用LocalStorageService.setItem存储纯token字符串,而非整个TokenModel对象:

// 登录成功回调示例(需在登录组件中补充)
this.authService.login(loginModel).subscribe(response => {
  if (response.success) {
    // 仅存储token字符串,而非整个响应对象
    this.localStorageService.setItem("token", response.data.accessToken);
  }
});

3. 增强AuthService的健壮性

增加token不存在或解析失败的容错处理,避免后续逻辑崩溃:

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { LoginModel } from '../models/loginModel';
import { SingleResponseModel } from '../models/singleResponseModel';
import { TokenModel } from '../models/tokenModel';
import { LocalStorageService } from './local-storage.service';
import { UserPasswordModel } from '../models/userPasswordModel';
import { ResponseModel } from '../models/responseModel';
import { JwtHelperService } from '@auth0/angular-jwt';

@Injectable({
  providedIn: 'root'
})
export class AuthService {
  apiUrl="https://localhost:5001/api/auth/";
  public jwtHelperService: JwtHelperService = new JwtHelperService();

  constructor(private httpClient:HttpClient,
    private localStorageService:LocalStorageService) {}

  login(user:LoginModel){
    return this.httpClient.post<SingleResponseModel<TokenModel>>(this.apiUrl+"login", user);
  }

  isAuthenticated(){
    return !!this.localStorageService.getItem("token");
  }

  updatePassword(userPasswordModel:UserPasswordModel){
    let newUrl = this.apiUrl + "updatepassword";
    return this.httpClient.post<ResponseModel>(newUrl, userPasswordModel)
  }

  get getDecodedToken() {
    let token = this.localStorageService.getItem("token");
    if (!token) return {};
    try {
      return this.jwtHelperService.decodeToken(token);
    } catch (error) {
      console.error("Token解析失败:", error);
      return {};
    }
  }

  get getCurrentUserId() {
    let decodedToken = this.getDecodedToken;
    if (!decodedToken) return 0;
    let userIdString = Object.keys(decodedToken).filter((t) =>
      t.endsWith('/nameidentifier')
    )[0];
    return userIdString ? Number(decodedToken[userIdString]) : 0;
  }
}

4. 优化UserComponent初始化逻辑

增加登录状态校验,避免未登录时执行用户信息获取逻辑:

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ToastrService } from 'ngx-toastr';
import { User } from 'src/app/models/user';
import { AuthService } from 'src/app/services/auth.service';
import { ProfileService } from 'src/app/services/profile.service';

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

  user:User;
  profileForm:FormGroup;
  passwordForm:FormGroup;
  dataLoaded = false;

  constructor(
    private userService:ProfileService,
    private authService:AuthService,
    private formBuilder:FormBuilder,
    private toastrService:ToastrService
  ) { }

  ngOnInit(): void {
    if (this.authService.isAuthenticated()) {
      this.getUserById();
    } else {
      this.toastrService.warning("请先登录");
      // 可选:跳转到登录页
      // this.router.navigate(['/login']);
    }
    this.createProfileForm();
    this.createPasswordForm();
  }

  createProfileForm(){
    this.profileForm = this.formBuilder.group({
      id:[Number(this.authService.getCurrentUserId)],
      firstName: ["",Validators.required],
      lastName:["",Validators.required]
    })
  }

  createPasswordForm(){
    this.passwordForm = this.formBuilder.group({
      userId:[Number(this.authService.getCurrentUserId)],
      oldPassword: ["",Validators.required],
      newPassword:["",Validators.required],
      repeatNewPassword:["",Validators.required]
    })
  }

  getUserById(){
    this.userService.getUserById(this.authService.getCurrentUserId)
      .subscribe(response=>{
        this.user = response.data
        this.dataLoaded = true
      }, error => {
        this.toastrService.error("用户信息获取失败");
      });
  }

  updateUserNames(){
    if (this.profileForm.valid) {
      let userModel = Object.assign({}, this.profileForm.value);
      this.userService.updateUserNames(userModel).subscribe(response=>{
        this.toastrService.info(response.message, "Bilgiler Güncellendi.");
        setTimeout(() => {
          window.location.reload();
        }, 1000);
      }, responseError=>{
        console.log(responseError);
        
        this.toastrService.error(responseError.error, "Hata!");
      });
      
    } else {
      this.toastrService.error("Lütfen tüm alanları doldurunuz.", "Hata!");
    }
  }

  updatePassword(){
    if (this.passwordForm.valid) {
      let passwordModel = Object.assign({}, this.passwordForm.value);
      console.log(passwordModel);
      this.authService.updatePassword(passwordModel).subscribe(response=>{
        this.toastrService.info(response.message, "Şifre Güncellendi");
      }, responseError=>{
        this.toastrService.error(responseError.error, "Hata!");
      });
    } else {
      this.toastrService.error("Lütfen tüm alanları doldurunuz.", "Hata!");
    }
  }
}

内容的提问来源于stack exchange,提问作者Mert Kont

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 09:11:31