Прокрутите объект JSON в Angular 5 и отобразите в таблице

Я получаю список из веб-API в формате JSON, и я использовал RXJS для чтения данных из веб-API и установки наблюдаемых, которые привязаны к строго типизированным. Мне нужно распечатать эти значения в шаблоне

интерфейс

export interface IMessageA{
id: number;
title: string;
detail: string;

}

обслуживание

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';

import{ IMessageA } from '../../../Interfaces/UnitTest/TestMessageA';

@Injectable()

export class ServerFlowTestService{

 private developmentBaseUrl: string = 'https://localhost:44370/';

 constructor(private http: Http){}

 public getMessageFromWebAPI_T1():Observable<IMessageA[]>
 {
    return this.http.get(this.developmentBaseUrl+ '/ant/analysis/GetMessage')
                    .map((response:Response)=> <IMessageA[]>response.json())

  }
    public getServerFlowTest1():string{
      return "this is test 1";
   }
  }

компонент, где я установил наблюдаемый

constructor(private unitTestingService: ServerFlowTestService 

 ) { 

this.unitTest1 = unitTestingService.getServerFlowTest1();

 this.unitTestingService.getMessageFromWebAPI_T1()
                      .subscribe((messageA_Data) => this.unitTestA = messageA_Data);

}

Шаблон

это работает, но показывает только объект

 <div class="animated fadeIn">
   Server Flow Test 1:: {{unitTestA}}
 </div> 

Это не работает, где нужна помощь

<div class="table-responsive">
   <table class="table" *ngIf='unitTestA && unitTestA.length'>
     <thead>
        <tr>             
              <th>Id</th>
              <th>Message</th>
              <th>Detail</th>              
        </tr> 
     </thead>
    <tbody>
      <tr *ngFor ="let messages of unitTestA">
          <td>{{messages.id }}</td>
          <td>{{messages.title }}</td>
          <td>{{messages.detail}}</td>
      </tr>
    </tbody>
 </table>
</div>   

Вернуть json-объект

[
  {
    "id": 1,
    "name": "item A",
    "isComplete": true
  },
  {
    "id": 2,
    "name": "item B",
    "isComplete": false
  },
  {
    "id": 3,
    "name": "item C",
    "isComplete": true
  },
  {
    "id": 4,
    "name": "item D",
    "isComplete": true
  }
]

ошибка

 Can't bind to 'ngForOf' since it isn't a known property of 'tr'. ("
  </thead>
  <tbody>
      <tr [ERROR ->]*ngFor ="let messages of unitTestA">
          <td>{{messages.id }}</td>
          <td>{{me"): ng:///DashboardModule/DashboardComponent.html@23:14
 Property binding ngForOf not used by any directive on an embedded template. 
 Make sure that the property name is spelled correctly and all directives 
 are listed in the "@NgModule.declarations". ("
  </thead>
  <tbody>
      [ERROR ->]<tr *ngFor ="let messages of unitTestA">
          <td>{{messages.id }}</td>
          <td>"): ng:///DashboardModule/DashboardComponent.html@23:10
 Can't bind to 'ngIf' since it isn't a known property of 'table'. ("

 <div class="table-responsive">
 <table class="table" [ERROR ->]*ngIf='unitTestA?.length > 0'>
    <thead>
      <tr>             
    "): ng:///DashboardModule/DashboardComponent.html@14:23
 Property binding ngIf not used by any directive on an embedded template. 
 Make sure that the property name is spelled correctly and all directives 
 are listed in the "@NgModule.declarations". ("

  <div class="table-responsive">
   [ERROR ->]<table class="table" *ngIf='unitTestA?.length > 0'>
     <thead>
      <tr>             
  "): ng:///DashboardModule/DashboardComponent.html@14:2
  Error: Template parse errors:
  Can't bind to 'ngForOf' since it isn't a known property of 'tr'. ("
    </thead>
      <tbody>
      <tr [ERROR ->]*ngFor ="let messages of unitTestA">
          <td>{{messages.id }}</td>
          <td>{{me"): ng:///DashboardModule/DashboardComponent.html@23:14
    Property binding ngForOf not used by any directive on an embedded 
     template. Make sure that the property name is spelled correctly and all 
   directives are listed in the "@NgModule.declarations". ("
  </thead>
  <tbody>
      [ERROR ->]<tr *ngFor ="let messages of unitTestA">
          <td>{{messages.id }}</td>
          <td>"): ng:///DashboardModule/DashboardComponent.html@23:10
  Can't bind to 'ngIf' since it isn't a known property of 'table'. ("

person Toxic    schedule 19.01.2018    source источник
comment
как выглядит ваш unitTestA   -  person Sajeetharan    schedule 19.01.2018
comment
это формат json, я обновил свой вопрос, см. внизу   -  person Toxic    schedule 19.01.2018


Ответы (2)


Это может быть полезно, Невозможно привязать к 'ngForOf', так как это неизвестное свойство 'tr' (окончательный выпуск).

Два предложения из этого вопроса, которые вы можете попробовать (скорее всего, второе):

Добавьте BrowserModule в imports: [] в @NgModule(), если это корневой модуль, иначе CommonModule.

а также

Вы должны импортировать «CommonModule» в компонент, где вы используете эти встроенные директивы, такие как ngFor, ngIf и т. д.

person Richard Matsen    schedule 19.01.2018

Изменить: сообщение об ошибке указывает, что у вас нет импорта BrowserModule в корневом модуле вашего приложения. Сначала импортируйте BrowserModule.

Затем в шаблоне попробуйте заменить

<table class="table" *ngIf='unitTestA && unitTestA.length'>

с

<table class="table" *ngIf='unitTestA?.length > 0'>
person Alok Jha    schedule 19.01.2018
comment
все еще не работает... следующая ошибка вставляется в мой вопрос - person Toxic; 19.01.2018