簡體   English   中英

語法錯誤:Angular 中的意外標記

[英]SyntaxError: Unexpected token in Angular

我想將我的網站添加為用戶的個人資料更新程序。 但是當我嘗試在我的網站上打開用戶的個人資料時,我在 Angular 中遇到了錯誤:

main.ts:6 ERROR SyntaxError: Unexpected token 'e', "eyJhbGciOi"... is not valid JSON
    at JSON.parse (<anonymous>)
    at LocalStorageService.getItem (local-storage.service.ts:17:22)
    at get getDecodedToken [as getDecodedToken] (auth.service.ts:39:42)
    at get getCurrentUserId [as getCurrentUserId] (auth.service.ts:44:29)
    at UserComponent.getUserById (user.component.ts:51:51)
    at UserComponent.ngOnInit (user.component.ts:28:10)
    at callHook (core.mjs:2752:22)
    at callHooks (core.mjs:2721:17)
    at executeInitAndCheckHooks (core.mjs:2672:9)
    at refreshView (core.mjs:12084:21)`

我的 local-storage.service.ts:

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);
    let value = JSON.parse(json);
    return value;
  }

  isSaved(key: string) {
    if (localStorage.getItem(key)) {
      return true;
    }
    return false;
  }

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

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

auth.service.ts:

`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(){
    if (localStorage.getItem("token")) {
      return true;
    }else{
      return false;
    }
  }

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

  get getDecodedToken() {
    let token = this.localStorageService.getItem("token");
    return this.jwtHelperService.decodeToken(token);
  }

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

用戶.component.ts:

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 {
    this.getUserById();
    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
      });
  }

  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!");
    }
  }
}

我該如何解決這個錯誤? 謝謝。 我嘗試了很多事情,但沒有人幫助我。

我正在嘗試添加用戶的個人資料更新程序。 但是這個錯誤...

正如錯誤所說; Unexpected token 'e', "eyJhbGciOi"... is not valid JSON 您正在嘗試解析表示令牌本身的純字符串,而不是表示 json object 的有效字符串。因此在嘗試解析它時失敗。

要么更新直接將令牌作為字符串存儲在本地存儲中的代碼,要么只使用localStorage.getItem('token')而不進行解析。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM