为什么在我的Angular应用中* ngIF总是评估为true?

时间:2018-10-14 15:35:10

标签: angular typescript angular-ng-if ngif

我对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>&#10003;</span></span>
  <ng-template #elseBlock>
    <span>&#x2715;</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
}
]

1 个答案:

答案 0 :(得分:6)

我确定completestring而不是boolean的代名词。

由于*ngIf(通常在JavaScript if(...)中)中的字符串始终解析为true(只要它不为空('')),{ {1}}块始终显示在屏幕上,而*ngIf则没有。

使用此修复它:

elseBlock