【发布时间】:2021-02-16 01:36:37
【问题描述】:
关于下面的代码,我有两个问题。我遇到的问题会在我遇到问题的代码行之后进行注释。
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[]'.
}
}
- 为什么我不能只在 Angular 中声明一个变量?为什么我应该总是用一个空值来初始化它来绕过错误?
- 如何修复错误“ts2322”?这个错误的原因是什么?
谢谢,
【问题讨论】:
-
这行得通吗? .subscribe(todos => this.todos = todos.body ?? []);
-
它有效。谢谢!
标签: angular typescript declaration