Observable 出现不可分配给 null 错误
Observable is getting a not assignable to null error
我有这个错误:
错误 TS2322:类型 'Observable<any[]>' 不可分配给类型 'null'。
对于此代码:
import { Component, OnInit } from '@angular/core';
import {HttpClient} from "@angular/common/http";
@Component({
selector: 'app-articles',
templateUrl: './articles.component.html',
styleUrls: ['./articles.component.css']
})
export class ArticlesComponent implements OnInit {
articles$ = null;
constructor(private httpClient: HttpClient) { }
ngOnInit(): void {
// @ts-ignore
this.articles$ = this.httpClient.get<any[]>('http://localhost:3000/articles');
}
}
我添加了:// @ts-ignore 这样它就可以绕过错误并打印我的数据库内容。
但这当然是一个临时解决方案,我想摆脱这个错误。
我认为显示错误是因为您没有定义 articles$
的类型
您可以通过在初始声明期间定义类型来解决此问题,如下所示。
articles$:Observable<ArticleModel[]> = null;
或者,您可以只删除初始分配的空值。
问题是你设置了articles$ = null
;这意味着它的类型是 null
。
要修复类型错误,您可以这样做
articles$: null | Observable<any[]> = null;
我更喜欢这样做。 ?
告诉编译器它可能未定义
articles$?: Observable<any[]>; // type is: undefined | Observable<any[]>
我有这个错误:
错误 TS2322:类型 'Observable<any[]>' 不可分配给类型 'null'。
对于此代码:
import { Component, OnInit } from '@angular/core';
import {HttpClient} from "@angular/common/http";
@Component({
selector: 'app-articles',
templateUrl: './articles.component.html',
styleUrls: ['./articles.component.css']
})
export class ArticlesComponent implements OnInit {
articles$ = null;
constructor(private httpClient: HttpClient) { }
ngOnInit(): void {
// @ts-ignore
this.articles$ = this.httpClient.get<any[]>('http://localhost:3000/articles');
}
}
我添加了:// @ts-ignore 这样它就可以绕过错误并打印我的数据库内容。
但这当然是一个临时解决方案,我想摆脱这个错误。
我认为显示错误是因为您没有定义 articles$
您可以通过在初始声明期间定义类型来解决此问题,如下所示。
articles$:Observable<ArticleModel[]> = null;
或者,您可以只删除初始分配的空值。
问题是你设置了articles$ = null
;这意味着它的类型是 null
。
要修复类型错误,您可以这样做
articles$: null | Observable<any[]> = null;
我更喜欢这样做。 ?
告诉编译器它可能未定义
articles$?: Observable<any[]>; // type is: undefined | Observable<any[]>