组件输入的值未定义为角度

时间:2017-08-07 03:22:29

标签: javascript angular ngrx ngrx-store ngrx-effects

我正在尝试将帖子从一个组件传递到另一个具有编辑表单的组件。外部组件获取帖子并传递给内部组件进行编辑,但由于某种原因它没有通过,所以我得到了一堆未定义的错误。

外部组件html如下所示:

<wie-edit-post-form *ngIf="post | async; else loading"></wie-edit-post-form>
<ng-template #loading>
    <wie-loading></wie-loading>
</ng-template>

外部组件打字稿如下所示:

import { Component, OnInit } from '@angular/core';
import {ActivatedRoute, Router} from '@angular/router';
import { Store } from '@ngrx/store';

import { Observable } from 'rxjs/Observable';

import {Post} from "../../common/models/post.model";

import * as fromRoot from '../../common/reducers';
import * as post from '../../common/actions/posts.actions';

@Component({
    selector: 'wie-edit-post',
    templateUrl: "./edit-post.component.html",
    styleUrls: ['./edit-post.component.html']
})
export class EditPostComponent {

    public post: Observable<Post>;

    constructor(private route: ActivatedRoute, private router: Router, private store: Store<fromRoot.State>) {

        this.route.params.subscribe((params) => {
            this.post = this.store.select(fromRoot.getSelectedPost).filter((storePost) => (storePost && storePost.id == parseInt(params.id, 10)) ).map((storePost) => {console.log(storePost); return storePost; });
            this.store.dispatch( new post.LoadPostAction((parseInt(params.id, 10))) );
        })
    }


}

内部组件html如下所示:

<md-card>
    <md-card-header>
        <md-card-title>
            <h1>Edit Post</h1>
        </md-card-title>
    </md-card-header>
    <md-card-content>
        <md-input-container>
            <textarea [(ngModel)]="post.content" mdInput placeholders="Prank"></textarea>
        </md-input-container>
    </md-card-content>
    <md-card-actions>
        <button md-raised-button>Cancel</button>
        <button color="accent" md-raised-button>Edit</button>
    </md-card-actions>
</md-card>

内部组件打字稿如下所示:

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

@Component({
    selector: 'wie-edit-post-form',
    templateUrl: './edit-post-from.component.html'
})
export class EditPostFormComponent implements OnInit {

    @Input()post: Post;

    ngOnInit() {
        console.log(this.post);
    }
}

store.select语句中的外部组件console.log正确地将帖子打印到控制台,但ngOnInit函数中的内部组件的console.log语句表明它未定义,因此商店正确调度LoadPostAction并从服务器获取帖子但在内部组件中我不断收到错误,即post.content未定义且帖子内容从未显示在表单中。

任何帮助将不胜感激。感谢

1 个答案:

答案 0 :(得分:1)

所以...这是愚蠢的事情,我实际上并没有将帖子传递给组件。我有$ngIF="post | async; else loading",但我没有[post]="post | async"