【问题标题】:Angular Service Issue Type string | nullAngular 服务问题类型字符串 |空值
【发布时间】:2022-01-06 02:04:11
【问题描述】:

我的 Angular 代码有这个问题,顺便说一下,我在我的应用程序中使用了 Angular 13。 问题在于调用服务我试图从后端调用用户 api 并且一直面临这个问题。 我进行了很多搜索并尝试了一切以使其正常工作,但没有任何解决方案。 这是下面的代码: 这是用户服务:

import { HttpClient, HttpResponse } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { JwtHelperService } from '@auth0/angular-jwt';
import { environment } from 'src/environments/environment';
import { User } from "../module/user";

@Injectable({providedIn: 'root'})
export class UserService {
  public apiUrl = environment.apiUrl;
  private jwtHelper = new JwtHelperService();

  constructor(private http: HttpClient) {}

  login(user: User): Observable<HttpResponse<User>> {
    return this.http.post<User>(`${this.apiUrl}/user/login`, user, { observe: 'response'});
  }

  register(user: User): Observable<HttpResponse<User>> {
    return this.http.post<User>(`${this.apiUrl}/user/register`, user, { observe: 'response'});
  }

  updateUser(formData: FormData): Observable<User> {
    return this.http.post<User>(`${this.apiUrl}/user/update`, formData);
  }

  deleteUser(username: string): Observable<any> {
    return this.http.delete<any>(`${this.apiUrl}/user/delete/${username}`);
  }

  addUserToCache(user: User): void {
    localStorage.setItem('user', JSON.stringify(user));
  }

  getUserFromCache(): User {
    return JSON.parse(localStorage.getItem('user'));
  }

  addTokenToCache(token: string): void {
    localStorage.setItem('token', token);
  }

  getTokenFromCache(): string {
    return localStorage.getItem('token');
  }

  logOut(): void {
    localStorage.removeItem('user');
    localStorage.removeItem('token');
  }

  getTokenExpirationDate(): Date | null {
    return this.jwtHelper.getTokenExpirationDate(this.getTokenFromCache());
  }

  isUserLoggedIn(): boolean {
    if (this.getTokenFromCache() && this.getUserFromCache() &&
      this.jwtHelper.decodeToken(this.getTokenFromCache()).sub &&
      !this.jwtHelper.isTokenExpired(this.getTokenFromCache())) {
      return true;
    } else {
      this.logOut();
      return false;
    }
  }

  createUserFormData(currentUsername: string, user: User): FormData {
    const formData = new FormData();
    formData.append('currentUsername', currentUsername);
    formData.append('username', user.username);
    formData.append('email', user.email);
    formData.append('role', user.role);
    formData.append('isActive', JSON.stringify(user.active));
    formData.append('isNonLocked', JSON.stringify(user.notLocked));
    return formData;
  }
}

这是用户数据

export class User {
  constructor(
    public id = 0,
    public userId = '',
    public username = '',
    public email = '',
    public lastLoginDate = null,
    public logInDateDisplay = null,
    public joinDate = null,
    public active = true,
    public notLocked = true,
    public role = '',
    public authorities = []) {}

}

这是显示给我的错误:

Error: src/app/role/admin/admin.component.ts:15:22 - error TS2339: Property 'getAdmin' does not exist on type 'UserService'.

15     this.userService.getAdmin().subscribe(
                        ~~~~~~~~


Error: src/app/role/admin/admin.component.ts:16:7 - error TS7006: Parameter 'data' implicitly has an 'any' type.

16       data => {
         ~~~~


Error: src/app/role/admin/admin.component.ts:19:7 - error TS7006: Parameter 'err' implicitly has an 'any' type.

19       err => {
         ~~~


Error: src/app/service/user.service.ts:36:23 - error TS2345: Argument of type 'string | null' is not assignable to parameter of type 'string'.
  Type 'null' is not assignable to type 'string'.

36     return JSON.parse(localStorage.getItem('user'));
                         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~


Error: src/app/service/user.service.ts:44:5 - error TS2322: Type 'string | null' is not assignable to type 'string'.
  Type 'null' is not assignable to type 'string'.

44     return localStorage.getItem('token');
       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~




** Angular Live Development Server is listening on localhost:4200, open your browser on http://localhost:4200/ **


✖ Failed to compile.
✔ Browser application bundle generation complete.

5 unchanged chunks

Build at: 2021-11-29T07:19:50.781Z - Hash: 1847dd9fe6fe2628 - Time: 350ms

Error: src/app/role/admin/admin.component.ts:15:22 - error TS2339: Property 'getAdmin' does not exist on type 'UserService'.

15     this.userService.getAdmin().subscribe(
                        ~~~~~~~~


Error: src/app/role/admin/admin.component.ts:16:7 - error TS7006: Parameter 'data' implicitly has an 'any' type.

16       data => {
         ~~~~


Error: src/app/role/admin/admin.component.ts:19:7 - error TS7006: Parameter 'err' implicitly has an 'any' type.

19       err => {
         ~~~


Error: src/app/service/user.service.ts:36:23 - error TS2345: Argument of type 'string | null' is not assignable to parameter of type 'string'.
  Type 'null' is not assignable to type 'string'.

36     return JSON.parse(localStorage.getItem('user'));
                         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~


Error: src/app/service/user.service.ts:44:5 - error TS2322: Type 'string | null' is not assignable to type 'string'.
  Type 'null' is not assignable to type 'string'.

44     return localStorage.getItem('token');
       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~




✖ Failed to compile.


【问题讨论】:

  • 您提供的代码中没有getAdmin() 函数,这也是您遇到的第一个错误。

标签: javascript json angular api rest


【解决方案1】:

尝试使用 any 而不是 User 作为参考,这样可以帮助您获取对象

getUserFromCache(): any { return JSON.parse(localStorage.getItem('user')); }

请先在 UserService 类中编写 getAdmin() 函数以解决此问题

【讨论】:

    【解决方案2】:

    没错,当你从localStorage中取元素时返回的类型是null或者string,

    getItem(key: string): string | null;
    

    你不能解析空值,在JSON.parse之前你必须确保项目存在并且你得到它

    【讨论】:

      【解决方案3】:

      试试这个

      return localStorage.getItem('token') || '';
      

      这只会解决 tsc 编译器问题。

      【讨论】:

      • 最好解释一下为什么确实需要这样做。
      【解决方案4】:

      服务中没有调用函数

      getAdmin()

      在调用之前在服务中实现该功能。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-07-08
        • 2010-12-06
        • 2019-07-13
        • 2017-08-24
        • 2011-09-09
        相关资源
        最近更新 更多