【发布时间】:2020-11-16 02:08:43
【问题描述】:
所以我在 4 天前开始尝试 Angular。
到目前为止,我想从我的后端 Flask 服务器获取一些多汁的 JSON 数据到我的前端 Angular。
问题是
- JSON 数据未保存到我的变量中
- 无法迭代
我不知道我做错了什么,现在寻求您的帮助。
JSON 文件具有这种结构。
{"id":[1,2,3],"name":["Test 1","Test 2","Test 3"]}
在我的浏览器中显示。
Error: "Error trying to diff 'Test 1,Test 2,Test 3'. Only arrays and iterables are allowed"
在我在评论者指出它不是我使用的数组之前提出的问题中,因此我无法迭代测试。
<ul>
<li *ngFor="let test of tests">
<a routerLink="/detail/{{test.id}}">
<span>{{test.id}}</span> {{test.name}}
</a>
</li>
</ul>
但是当这段代码改为
<ul>
<li *ngFor="let test of tests.id">
<a routerLink="/detail/{{test}">
<span>{{test.id}}</span>
</a>
</li>
</ul>
尝试构建时出现错误。说error TS2339: Property 'id' does not exist on type 'Test[]'.
但是接口已经定义了这些(id 和 name),所以我从中得出的唯一结论是测试必须是空的。
我的 tests.service.ts 应该得到一个类型测试的 Observable 数组
...
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();
}
}
使用的测试接口。
export interface Test {
id: number;
name: string;
}
Console.log(tests) 返回空。
也许你们中的某个人可以提供帮助并指出问题出在哪里。
干杯!
编辑:
增加了测试接口。
【问题讨论】:
-
你的 Test[] 类型定义在哪里?
-
添加了请看一下。
标签: angular typescript flask-restful