我将数据打印到日志中。我只是把它放在一个数组中吗?所以我可以做到
<ul *ngIf="courses$ | async as courses else noData">
<li *ngFor="let course of courses">
{{course.name}}
</li>
</ul>
<ng-template #noData>No Data Available</ng-template>
export class SurveyComponent {
surveys: Survey[];
survey: Survey;
constructor(private http: HttpClient) {
}
ngOnInit(): void {
this.http.get('http://localhost:54653/api/survey/').subscribe(data => {
console.log(data);
},
err => {
console.log('Error occured.');
}
);
}
}
export class Survey {
constructor(id?: string, name?: string, description?: string) {
this.id = id;
this.name = name;
this.description = description;
}
public id: string;
public name: string;
public description: string;
}
编辑1:为什么第一个.map工作而另一个不工作?
答案 0 :(得分:1)
您可以在API调用后使用rxjs map
运算符:
...
courses$: Observable<Survey[]>
...
ngOnInit(): void {
// if you want use the async pipe in the view, assign the observable
// to your property and remove .subscribe
this.courses$ = this.http
.get('http://localhost:54653/api/survey/')
.map(surveys =>
surveys.map(survey => new Survey(survey.id, survey.name, survey.description))
)
}
...
答案 1 :(得分:1)
喜欢这个吗?
surveys$: Observable<Survey[]>;
ngOnInit(): void {
this.surveys$ = this.http.get<Survey[]>('http://localhost:54653/api/survey/');
}