punkouter
punkouter

Reputation: 5366

Simple attempt to get json data into an array

I have the data being printed out to a log . Have do I simply put this in an array? So I can do

   <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

EDIT 1: Why does the first .map work and the other doesn't ?

enter image description here

Upvotes: 0

Views: 55

Answers (2)

pioro90
pioro90

Reputation: 694

Like this ?

surveys$: Observable<Survey[]>;

ngOnInit(): void {
  this.surveys$ = this.http.get<Survey[]>('http://localhost:54653/api/survey/');
}

Upvotes: 1

mickaelw
mickaelw

Reputation: 1513

You can use rxjs map operator after your API call:

...
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))
     )
}
...

Upvotes: 1

Related Questions