[英]Getting error trying to pass data to child component in angular
我是 angular 的新手,我有一個組件如下
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
constructor(private http: HttpClient) { }
blogpost;
ngOnInit() {
this.http.get("http://localhost:8080/demo/all").
subscribe(function(data){
this.blogpost=data;
console.log(this.blogpost);
})
}
}
blogpost 字段包含一組 blogposts 對象,這里是與組件關聯的模板
<div class="row">
<div class="col-sm-6">
</div>
<div class="col-sm-6">
<div class="row">
<div class="col-sm-6"><app-blog-post [title]="blogpost[0].title"></app-blog-post></div>
<div class="col-sm-6">456</div>
</div>
<div class="row">
<div class="col-sm-6">123</div>
<div class="col-sm-6">456</div>
</div>
</div>
</div>
但是從這個模板傳遞的值沒有顯示在子組件中,並且我收到錯誤TypeError: Cannot read property '0' of undefined
這里是子組件
import { Component, OnInit, Input } from '@angular/core';
@Component({
selector: 'app-blog-post',
templateUrl: './blog-post.component.html',
styleUrls: ['./blog-post.component.css']
})
export class BlogPostComponent implements OnInit {
ngOnInit() {
}
@Input() title:String="abc";
}
和子模板
<div>{{title}}</div>
我無法弄清楚出了什么問題。 請有人幫我解決這個問題
將博客文章移出構造函數,然后將其聲明為
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
public blogpost: Array<any> = [];
constructor(private http: HttpClient) { }
ngOnInit() {
this.http.get("http://localhost:8080/demo/all").
subscribe(function(data){
this.blogpost=data;
console.log(this.blogpost);
})
}
}
不要忘記 http 調用是異步的,因此在 get 請求完成之前不會定義 Post 列表。 因此 undefined 的索引 0 無效。 一種解決方案可能是在 app-blog-post 組件上使用 ˋ*ngIf="!!blogpost"。
更好的解決方案可能是使用異步管道。 這是一個很好的例子: https : //medium.com/angular-in-depth/angular-question-rxjs-subscribe-vs-async-pipe-in-component-templates-c956c8c0c794
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.