我对Todo
的定义如下:
export class Todo {
id: number;
title: string;
complete: boolean = false;
editMode: boolean = false;
}
我有以下数据服务:
getAllTodos(): Observable<Array<Todo>> {
return this.aHttpService.get<Array<Todo>>('http://localhost:3000/todos');
}
然后,我有这个组件:
import { Component, OnInit } from '@angular/core';
import { TodoDataService } from '../todo-data.service';
import { Todo } from '../todo';
import { Observable } from 'rxjs/Observable';
@Component({
selector: 'app-all-tasks',
templateUrl: './all-tasks.component.html',
styleUrls: ['./all-tasks.component.css']
})
export class AllTasksComponent implements OnInit {
constructor(private todoDataService: TodoDataService) {}
allTodos: Observable<Array<Todo>>;
ngOnInit() {
this.allTodos = this.todoDataService.getAllTodos();
}
}
在模板中,我有:
<li *ngFor="let todo of allTodos | async" >
<span *ngIf="todo.complete; else elseBlock"><span>✓</span></span>
<ng-template #elseBlock>
<span>✕</span>
</ng-template>
<span>{{todo.title}}</span>
</li>
尽管输入数据并不总是todo.complete
,但是true
总是求值为true
。 (我通过与邮递员联系该服务来验证这一点...)
为什么值总是true
?
我应该注意todo.title
的渲染正确。
更新
通过邮递员致电http://localhost:3000/todos
会返回:
[
{
"id": 1,
"title": "Learn TypeScript",
"complete": "true",
"editMode": "false"
},
{
"id": 2,
"title": "Learn Angular changed",
"complete": "true",
"editMode": "false"
},
{
"id": 3,
"title": "Learn to Read",
"complete": "true",
"editMode": "false"
},
{
"id": 4,
"title": "Learn to Write",
"complete": "false",
"editMode": "false"
},
{
"title": "Learn how to type",
"complete": "true",
"editMode": "false",
"id": 5
},
{
"title": "Learn how to drive",
"complete": "false",
"editMode": "false",
"id": 6
}
]
答案 0 :(得分:6)
我确定complete
是string
而不是boolean
的代名词。
由于*ngIf
(通常在JavaScript if(...)
中)中的字符串始终解析为true
(只要它不为空(''
)),{ {1}}块始终显示在屏幕上,而*ngIf
则没有。
使用此修复它:
elseBlock