[英]How to add a new post first in the list of posts?
我想在組件GalleryComponent
(這是父組件)中使用getPictures getPictures()
方法添加新帖子,其中“ post.id”大於10,在列表中排在首位,而所有其他帖子“ post.id”依次少於10個。 我試圖使用方法getPictures()
的條件來執行此操作,但出現錯誤:“ TypeError:無法讀取未定義的屬性'unshift'和'push'”。
父組件代碼GalleryComponent:
export class GalleryComponent implements OnInit { collection: Picture[]; constructor(private galleryService: GalleryService) { } ngOnInit() { this.getPictures(); } getPictures() { this.galleryService.getPictures().subscribe((data: Picture[]) => { data.forEach(post => { if (post.id > 10) { this.collection.unshift(post); } else { this.collection.push(post); } }); }) } }
父組件模板GalleryComponent鏈接到組件GalleryAddComponent:
<a routerLink="/gallery-add" class="btn btn-outline-success tog"> Add New Post </a>
子組件代碼GalleryAddComponent:
export class GalleryAddComponent implements OnInit { isAdded: boolean = false; constructor( private galleryService: GalleryService) {} ngOnInit() { } addPost(title: string, url: string): void { this.galleryService.add(title, url).subscribe(res => { this.isAdded = true; }); } }
GalleryService對服務器的請求:
export class GalleryService { galleryUrl: string = 'http://localhost:5555/posts'; httpOptions: object = { headers: new HttpHeaders({'Content-Type': 'application/json'}) }; constructor(private http: HttpClient) {} getPictures(): Observable<Picture[]> { return this.http.get<Picture[]>(`${this.galleryUrl}`); } add(title: string, url: string): Observable<Picture> { const postObj = { title, url }; return this.http.post<Picture>(this.galleryUrl, postObj, this.httpOptions); } }
圖片模式:
export interface Picture { id: number, title: string, url: string }
僅供參考,請嘗試一次,
collection: Picture[]=[];
getPictures() {
this.galleryService.getPictures().subscribe((data: Picture[]) => {
data.forEach(post => {
if (post.id > 10) {
this.collection.splice(0,0,post); //here is updated one line
} else {
this.collection.push(post);
}
});
})
}
希望它能解決您的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.