source

string | null 형식의 인수는 string 유형의 파라미터에 할당할 수 없습니다.유형 'null'은 유형 'string'에 할당할 수 없습니다.

bestscript 2023. 2. 16. 22:01

string | null 형식의 인수는 string 유형의 파라미터에 할당할 수 없습니다.유형 'null'은 유형 'string'에 할당할 수 없습니다.

dotnetcore 20 및 angular4 프로젝트를 가지고 있으며 userService를 생성하여 사용자를 홈 컴포넌트로 이동시키려고 합니다.백엔드는 정상적으로 동작하지만 서비스는 동작하지 않습니다.local Storage에서 문제가 발생.에러 메시지는 다음과 같습니다.

string | null 형식의 인수는 string 유형의 파라미터에 할당할 수 없습니다.'null' 유형은 'string' 유형에 할당할 수 없습니다.

사용자 서비스

import { User } from './../models/users';
import { AppConfig } from './../../app.config';
import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions, Response } from '@angular/http';



@Injectable()
export class UserService {
constructor(private http: Http, private config: AppConfig) { }

getAll() {
    return this.http.get(this.config.apiUrl + '/users', this.jwt()).map((response: Response) => response.json());
}

getById(_id: string) {
    return this.http.get(this.config.apiUrl + '/users/' + _id, this.jwt()).map((response: Response) => response.json());
}

create(user: User) {
    return this.http.post(this.config.apiUrl + '/users/register', user, this.jwt());
}

update(user: User) {
    return this.http.put(this.config.apiUrl + '/users/' + user.id, user, this.jwt());
}

delete(_id: string) {
    return this.http.delete(this.config.apiUrl + '/users/' + _id, this.jwt());
}

// private helper methods

private jwt() {
    // create authorization header with jwt token
    let currentUser = JSON.parse(localStorage.getItem('currentUser'));
    if (currentUser && currentUser.token) {
        let headers = new Headers({ 'Authorization': 'Bearer ' + currentUser.token });
        return new RequestOptions({ headers: headers });
    }
}

그리고 나의 home.component.ts는

import { UserService } from './../services/user.service';
import { User } from './../models/users';
import { Component, OnInit } from '@angular/core';

@Component({
moduleId: module.id,
templateUrl: 'home.component.html'
})

export class HomeComponent implements OnInit {
currentUser: User;
users: User[] = [];

constructor(private userService: UserService) {
   this.currentUser = JSON.parse(localStorage.getItem('currentUser'));
}

ngOnInit() {
   this.loadAllUsers();
}

deleteUser(_id: string) {
   this.userService.delete(_id).subscribe(() => { this.loadAllUsers() });
}

private loadAllUsers() {
   this.userService.getAll().subscribe(users => { this.users = users; });
}

에러는 점등하고 있다.JSON.parse(localStorage.getItem('currentUser'));

에러에 나타나 있듯이localStorage.getItem()문자열 또는 를 반환 가능null.JSON.parse()문자열이 필요하므로 결과를 테스트해야 합니다.localStorage.getItem()사용해보기 전에.

예를 들어 다음과 같습니다.

this.currentUser = JSON.parse(localStorage.getItem('currentUser') || '{}');

또는 다음과 같은 경우가 있습니다.

const userJson = localStorage.getItem('currentUser');
this.currentUser = userJson !== null ? JSON.parse(userJson) : new User();

Willem De Nys의 답변도 참조하십시오.만약 당신이 확신한다면localStorage.getItem()콜이 반환되지 않는다nullnon-signed assertion 연산자를 사용하여 수행 중인 작업을 알고 있는 타이프스크립트를 알릴 수 있습니다.

this.currentUser = JSON.parse(localStorage.getItem('currentUser')!);

승인된 답변은 정확합니다.그냥 더 새롭고 짧은 답변을 추가하려고 합니다.

this.currentUser = JSON.parse(localStorage.getItem('currentUser')!);

Null이 아닌 어설션 연산자는 나에게 매우 효과가 있었습니다.

(1) 나의 경우

this.currentUserSource.next(null!)

(2) 고객님의 경우

this.currentUser = JSON.parse(localStorage.getItem('currentUser')!);

각도 또는 TS 사용:-

JSON.parse(localStorage.getItem('user') as string);

또는

JSON.parse(localStorage.getItem('user') as any);

string | null' 유형은 string 유형에 할당할 수 없습니다.'null' 유형은 'string' 유형에 할당할 수 없습니다.

export class TodoComponent implements OnInit {
  
  loacalitems!: string;
  todos!: Todo[];

  constructor() {
    this.loacalitems = localStorage.getItem("todos");
}

왜냐면localStorage.getItem()돌아가다string or null이 문제를 해결합니다. 이 유형의 오류는 변수 정의입니다.

localitems!: string | null;

이 변수는 값 문자열 또는 null을 유형으로 유지합니다. 그런 다음 논리를 작성합니다.

다른 경우에는 손이 짧다.

this.todos = this.localitems !== null ? JSON.parse(this.localitems) : [];

if-internal의

if(this.localitems !== null){
   // item not null code
   this.todos = JSON.parse(this.localitems)
}else{
   // item is null code
   this.todos = []
}
  localsetItem: string | null;
  constructor() { 
  this.localsetItem=localStorage.getItem("todos")
  if(this.localsetItem == null)
  {
    this.todos  = [];
  }
  else
      {
    this.todos=JSON.parse(this.localsetItem);
      }
   }

이거 드셔보세요

private userSubject$ = new BehaviorSubject<User | unknown>(null);

이에 대한 의견:

export const useStateWithLocalStorage = (defaultValue: string[], key: string) => {
  const [value, setValue] = useState(() => {
    const storedValues = localStorage.getItem(key);

    return storedValues !== null ? JSON.parse(storedValues) : defaultValue;
  });

  useEffect(() => {
    localStorage.setItem(key, JSON.stringify(value));
  }, [key, value]);

  return [value, setValue];
};

위의 솔루션을 사용하여 이 문제를 해결하는데 많은 어려움을 겪었지만, 모두 성공하지 못했습니다.나에게 효과가 있었던 것은:

   const serializableState: string | any = localStorage.getItem('globalState');
    return serializableState !== null || serializableState === undefined ? JSON.parse(serializableState) : undefined;

변수를 string | any에 캐스트하고 변수를 해석하기 전에 변수가 늘인지 정의되지 않았는지 확인해야 했습니다.

나는 아래와 같이 해결했다.

router.navigateByUrl(returnUrl!);

언급URL : https://stackoverflow.com/questions/46915002/argument-of-type-string-null-is-not-assignable-to-parameter-of-type-string