【问题标题】:How to pass data between angular components?如何在角度组件之间传递数据?
【发布时间】:2019-08-27 14:30:30
【问题描述】:

我不明白为什么我无法在我的 Angular 应用程序的两个组件之间传递数据。这是我所拥有的,但子组件返回“未定义”

我创建了一个对象数组,它只接收一个名为 profileFeedPosts 的字符串,并尝试将其传递给另一个组件,再次作为“Post”对象数组。

profile-feed 是父级,public-feed 是子级。也许我错过了一些关于在 Angular 中构建父/子组件的方式?

父组件:

 import { Component} from '@angular/core';
 import { Post } from "../models/post.model"



 @Component({
      selector: 'app-profile-feed',
      templateUrl: './profile-feed.component.html',
      styleUrls: ['./profile-feed.component.css']
    })
    export class ProfileFeedComponent  {

      postBody = null;

      profileFeedPosts: Post[] = [
        new Post("hello")
      ];

      showPostBody(){
        this.postBody = 1;
      }

      createPost(){
        this.postBody = null;
      }

      postSubmitted(post: string){
        const newPost = new Post(post);
        this.profileFeedPosts.push(newPost);
      }

      constructor() { }

      ngOnInit() {
      }

    }

父组件 HTML:

<div class="post-body" *ngIf="postBody">
  <input id="post" type="text" #userPost placeholder="What's up?">
  <button (click)="createPost(); 
postSubmitted(userPost.value);">Share</button>
</div>
<app-public-feed [childFeedPosts]="profileFeedPosts"></app-public- 
feed>

子组件:

    import { Component, Input } from '@angular/core';
    import { Post } from '../models/post.model';


    @Component({
      selector: 'app-public-feed',
      templateUrl: './public-feed.component.html',
      styleUrls: ['./public-feed.component.css']
    })

    export class PublicFeedComponent {

      @Input() childFeedPosts: Post[];




      constructor() { }

      ngOnInit() {
      }

    }

    console.log(this.childFeedPosts);

【问题讨论】:

  • 子组件返回“未定义”这是什么意思。返回未定义的方法是什么?鉴于最后一行不是 PublicFeedComponent 类的任何方法的一部分,代码如何编译?
  • Jack,如果您能在 stackblitz.com 上提供示例代码,那将非常有帮助。

标签: angular


【解决方案1】:

您已将console.log 放在组件类之外,进入全局范围,其中this.childFeedPosts 不存在。

尝试在PublicFeedComponent.ngOnInit 方法中移动console.log

【讨论】:

  • 伙计,非常感谢。我要疯了,以为所有的格式都正确。我现在觉得很傻。
猜你喜欢
  • 2020-09-12
  • 2019-09-25
  • 1970-01-01
  • 2018-03-13
  • 2017-01-12
  • 2020-04-22
  • 1970-01-01
  • 2018-09-14
  • 1970-01-01
相关资源
最近更新 更多