我对下面的代码有两个问题。在我遇到问题的代码行之后对我提出的问题进行了评论。
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[]'.
}
}
谢谢,
答案 0 :(得分:0)
这是因为您在 tsconfig.json
中启用了 Strict Property Initialization(或严格)。
有了这个,您必须直接或在构造函数中设置所有属性。
如果你不想用空数组赋值,并且你确定它会被初始化,你可以使用非空断言运算符:
todos!: Todo[];
或者您需要将其设为可选:
todos?: Todo[];