【问题标题】:Argument of type 'null' is not assignable to parameter Angular“null”类型的参数不能分配给参数 Angular
【发布时间】:2021-07-05 14:43:53
【问题描述】:
@Injectable({ providedIn: 'root' })
export class AuthenticationService {
    private currentUserSubject: BehaviorSubject<User>;
    public currentUser: Observable<User>;

    constructor(private http: HttpClient) {
        this.currentUserSubject = new BehaviorSubject<User>(JSON.parse(localStorage.getItem('currentUser')));
        this.currentUser = this.currentUserSubject.asObservable();
    }

    public get currentUserValue(): User {
        return this.currentUserSubject.value;
    }

    login(username: string, password: string) {
        return this.http.post<any>(`${environment.apiUrl}/users/authenticate`, { username, password })
            .pipe(map(user => {
                // store user details and jwt token in local storage to keep user logged in between page refreshes
                localStorage.setItem('currentUser', JSON.stringify(user));
                this.currentUserSubject.next(user);
                return user;
            }));
    }

    logout() {
        // remove user from local storage to log user out
        localStorage.removeItem('currentUser');
        this.currentUserSubject.next(null);
    }
}

知道为什么我在最后一行出现错误(this.currentUserSubject.next(null))? 错误消息:“null”类型的参数不可分配给“User”类型的参数。 最新的打字稿版本不允许这样做吗?另一种解决方案是什么?

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    Typescript 变得更严格了。

    您可以关闭严格模式或让您的 observable 接受 nulls:

    private currentUserSubject: BehaviorSubject<User | null>;
    

    【讨论】:

    • 如何关闭严格?
    • tsconfig中找到strictNullChecks并将其设置为false
    • 不要关闭严格模式,它的存在是有原因的:避免运行时出错!
    【解决方案2】:

    检查this.currentUserSubject.next(null); 是否真的需要

    【讨论】:

      【解决方案3】:

      最好的做法是你总是使用

      示例私有 currentUserSource = new ReplaySubject(1);

      然后你可以调用该函数 this.currentUserSource.next(null);或者最简单的是

      private currentUserSource = new ReplaySubject(1);

      那么 this.currentUserSource.next(); () 可以认为是 null

      【讨论】:

        【解决方案4】:

        Juts 像这样使用它:

        this.currentUserSubject.next();
        

        this.currentUserSubject = new BehaviorSubject<User | null>(JSON.parse(localStorage.getItem('currentUser')));
        

        【讨论】:

          猜你喜欢
          • 2022-06-23
          • 2021-12-22
          • 2018-04-05
          • 1970-01-01
          • 2019-04-27
          • 1970-01-01
          • 1970-01-01
          • 2021-09-30
          • 1970-01-01
          相关资源
          最近更新 更多