gpt4 book ai didi

javascript - 尝试以 Angular 方式将数据传递给子组件时出现错误

转载 作者:行者123 更新时间:2023-12-02 22:06:32 24 4
gpt4 key购买 nike

我是 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>

我不知道出了什么问题。请有人帮我解决这个问题

最佳答案

blogpost移出构造函数,然后将其声明为

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

}
}

关于javascript - 尝试以 Angular 方式将数据传递给子组件时出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59696952/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com