0

由于所有问题看起来都过时了,我在问这个问题。

首先我需要提一下,我在 4 天前才开始使用 Angular,所以请向你的孩子解释一切(或者类似的东西,哈哈)。

我目前尝试从 Flask Server 检索 JSON。

它有这种格式。

{"id":[1,2,3],"name":["Test 1","Test 2","Test 3"]}

这些示例将缺少导入,因为它在测试时正常工作,现在数据应该来自服务器。

当我尝试使用 *ngFor 进行迭代时,会出现以下错误。

Error: "Error trying to diff 'Test 1,Test 2,Test 3'. Only arrays and iterables are allowed"

用于此的 HTML 是:

<ul>
  <li *ngFor="let test of tests">
          <a routerLink="/detail/{{test.id}}">
          <span>{{test.id}}</span> {{test.name}}
          </a>
  </li>
</ul>

在我的 test.service.ts 中,它看起来如下。

...
import { HttpClient, HttpHeaders } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class TestService {

private testUrl = 'http://my.server/tests';

constructor(
  private http: HttpClient
  ) { }

getTests(): Observable<Test[]> {
        return this.http.get<Test[]>(this.testUrl);
        }
...

在我的 tests.component.ts 中是这样的:

...
@Component({
  selector: 'app-tests',
  templateUrl: './tests.component.html',
  styleUrls: ['./tests.component.css']
})
export class TestsComponent implements OnInit {
  tests: Test[];

  getTests(): void {
        this.testService.getTests()
                .subscribe(tests => this.tests = tests);

  }


  constructor(private testService: TestService) { }

  ngOnInit(): void {
  this.getTests();
  }

}

在试图弄清楚 2 小时后,我不知道该怎么做。

如果缺少什么,请告诉我。

干杯!

4

2 回答 2

0

从日志中可以看出,*ngForOf仅适用于数组。

{"id":[1,2,3],"name":["Test 1","Test 2","Test 3"]}

您收到此 json 对象(不是数组)并尝试在其上使用 *ngForOf。

于 2020-07-26T14:50:20.557 回答
0
let test of tests

这是你问题的根源。这不是可迭代对象或数组。tests.id 这些tests.name是数组。通过查看服务器的响应就很清楚了。ngFor将在tests.idor t上工作ests.nametests只是一个对象。

于 2020-07-26T14:45:38.137 回答