由于所有问题看起来都过时了,我在问这个问题。
首先我需要提一下,我在 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 小时后,我不知道该怎么做。
如果缺少什么,请告诉我。
干杯!