将 json 数据放入数组的简单尝试
Simple attempt to get json data into an array
我将数据打印到日志中。我只是把它放在一个数组中吗?所以我可以做
<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 有效而另一个无效?
您可以在 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))
)
}
...
像这样?
surveys$: Observable<Survey[]>;
ngOnInit(): void {
this.surveys$ = this.http.get<Survey[]>('http://localhost:54653/api/survey/');
}
我将数据打印到日志中。我只是把它放在一个数组中吗?所以我可以做
<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 有效而另一个无效?
您可以在 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))
)
}
...
像这样?
surveys$: Observable<Survey[]>;
ngOnInit(): void {
this.surveys$ = this.http.get<Survey[]>('http://localhost:54653/api/survey/');
}