简单地尝试将json数据放入数组中

时间:2017-12-11 14:39:01

标签: arrays json angular mapping angular-httpclient

我将数据打印到日志中。我只是把它放在一个数组中吗?所以我可以做到

   <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;

}

snip

编辑1:为什么第一个.map工作而另一个不工作?

enter image description here

2 个答案:

答案 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/');
}