关于下面的代码,我有两个问题。我所提出的问题是在我有问题的代码行之后进行评论的。
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { tap } from 'rxjs/operators';
interface Todo{
id: number,
content: string;
completed: boolean;
}
@Component({
selector: 'app-root',
template: `
<ul>
<li *ngFor="let todo of todos">{{ todo.content }}</li>
</ul>
<pre>{{ todos | json }}</pre>
`,
styles: []
})
export class AppComponent implements OnInit{
todos: Todo[] = []; //Why do I need to initialize it everytime? when I tried to just declare the variable, it throws an error.
url = 'http://localhost:3000/todos';
constructor(public http: HttpClient){}
ngOnInit(){
this.http.get<Todo[]>(this.url, {observe: 'response'})
.pipe(
tap(res => console.log(res)),
tap(res => console.log(res.headers)),
tap(res => console.log(res.status))
)
.subscribe(todos => this.todos = todos.body);**//TS2322**: Type 'Todo[] | null' is not assignable to type 'Todo[]'.Type 'null' is not assignable to type 'Todo[]'.
}
}谢谢,
发布于 2021-02-16 02:02:04
这是因为在您的严格属性初始化中启用了tsconfig.json (或严格)。这样,必须直接或在构造函数中设置所有属性。
如果您不想使用空数组进行赋值,并且确信它将被初始化,则可以使用非空断言运算符:
todos!: Todo[];或者你需要让它是可选的
todos?: Todo[];https://stackoverflow.com/questions/66217634
复制相似问题