我正在尝试将帖子从一个组件传递到另一个具有编辑表单的组件。外部组件获取帖子并传递给内部组件进行编辑,但由于某种原因它没有通过,所以我得到了一堆未定义的错误。
外部组件 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 未定义的错误,并且帖子内容从未出现在表单中。
任何帮助,将不胜感激。谢谢