[英]Populate the data in drop-down from a GET json response- Angular4
[英]Display data from json array using angular4
我是新手,所以請幫助我。 我有一個api返回包含名稱,位置ID的對象數組。
我需要在HTML頁面上的不同卡片中顯示此卡片,這些卡片是一個小部件。
在ngOnInit()
部分下的父組件中,如何訪問此json數據並遍歷數組,以便將其作為不同的卡片顯示在我的頁面上?
先感謝您。
import { Component, OnInit } from '@angular/core';
import {HttpClient} from '@angular/common/http';
import { Observable } from 'rxjs/observable';
@Component({
selector: 'app-home-page',
templateUrl: './home-page.component.html',
styleUrls: ['./home-page.component.css']
})
export class HomePageComponent implements OnInit {
showSplash = true
//public events: any = [];
events = [];
constructor(private http : HttpClient) { }
ngOnInit() {
this.showSplash = true
this.http.get("/events").subscribe(data => {
console.log("EVENTS ARE: ", data);
this.events = data;
console.log(this.events)
})
}
ngAfterViewInit(){
setTimeout(() => {
this.showSplash = false
}, 3000);
}
}
這將為您提供所需的事件。
import { Component, OnInit, OnDestroy } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Subscription } from 'rxjs';
@Component({
selector: 'app-home-page',
templateUrl: './home-page.component.html',
styleUrls: ['./home-page.component.css']
})
export class HomePageComponent implements OnInit, OnDestroy {
showSplash = true
events = [];
subscription: Subscription;
constructor(private http: HttpClient) {}
ngOnInit() {
this.subscription = this.http.get("/events").subscribe(data => {
this.events = data;
this.showSplash = false;
});
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
您將必須實現一個子組件( EventComponent
可能帶有選擇器app-event
),該子組件將事件對象接受為@Input
屬性。 然后,在HomePageComponent
模板中,您可以遍歷以下事件:
<div *ngFor="let event of events">
<app-event [event]="event"></app-event>
</div>
或者 :
您可以在HomePageComponent
的模板中使用async
管道,以避免手動取消訂閱Observable Subscription。 您的HomePageComponent
類代碼將更改為:
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-home-page',
templateUrl: './home-page.component.html',
styleUrls: ['./home-page.component.css']
})
export class HomePageComponent implements OnInit {
events$;
constructor(private http: HttpClient) {}
ngOnInit() {
this.events$ = this.http.get("/events");
}
}
然后在HomePageComponent的模板中:
<div *ngFor="let event of events$ | async">
<app-event [event]="event"></app-event>
</div>
在這種情況下,您的EventComponent
如下所示:
import { Component, Input, OnChanges } from '@angular/core';
@Component({
selector: 'app-event',
templateUrl: './event.component.html',
styleUrls: ['./event.component.css']
})
export class EventComponent implements OnChanges{
@Input() event;
ngOnChanges() {
this.events$ = this.http.get("/events");
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.