'null' 类型的参数不可分配给参数 Angular

时间:2021-04-09 17:36:51

标签: angular typescript

@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”类型的参数。 最新的打字稿版本不允许这样做吗?另一种解决方案是什么?

3 个答案:

答案 0 :(得分:3)

打字稿变得更加严格。您可以关闭严格模式或让您的 observable 也接受空值

div.SideNavContainer__content {
  padding: 1rem;
  margin: -1rem -1rem -1rem 0;
  z-index: 0;

  & div.Content_component > div.PriceProfileLanding {
    overflow-y: auto;
  }
}

答案 1 :(得分:1)

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

答案 2 :(得分:0)

像这样使用它:

this.currentUserSubject.next();

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