如何预先填充发布/编辑模板驱动的表单

问题描述 投票:0回答:1

所有,我有一个模板驱动的表单,用于发布“博客文章”和相同的表单来编辑“博客文章”。我在 Google 和 YouTube 上搜索并找到了一个教程来解释我的尝试,但它是 Angular 的旧版本,并且我得到很多类型 string|null 无法分配给字符串错误

我的想法建议使用赋值断言运算符,它可以消除错误,但不会填充表单。我在 Stackoverflow 上读到关于!运算符,这也消除了错误,但我仍然无法填充表单。我期望的是,每当我单击编辑按钮时,我用于发布的相同表单将填充数据库值(MongoDB)。

以下是代码:

create post component 

  post: Post | void | undefined;
  private mode = 'create';
  private postId: string | null | undefined;

  constructor(
    public postService: PostServiceService,
    public route: ActivatedRoute
  ) {}

  ngOnInit() {
    this.route.paramMap.subscribe((paramMap: ParamMap) => {
      if (paramMap.has('postId')) {
        this.mode = 'edit';
        this.postId = paramMap.get('postId');
        this.post = this.postService.getPost(this.post);
      } else {
        this.mode = 'create';
        this.postId = null;
      }
    });
  }

-------------------------------------------------------------------------------------------
post service

 getPost(post?: void | Post | undefined) {
    //return [...this.posts];
    this.http
      .get<{ message: string; posts: any }>('http://localhost:4000/api/posts')
      .pipe(
        map((postData) => {
          return postData.posts.map((post: any) => {
            return {
              title: post.title,
              content: post.content,
              id: post._id,
            };
          });
        })
      )
      .subscribe((transformedtData) => {
        this.posts = transformedtData;
        this.postsUpdated.next([...this.posts]);
      });
  }

-------------------------------------------------------------------------------------------
app routing

const routes: Routes = [
  { path: '', component: ListPostComponent },
  { path: 'create', component: CreatePostComponent },
  { path: 'edit/:postId', component: CreatePostComponent },
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
})
angular mongodb
1个回答
0
投票

我找到了答案:错误在于类型, post:Post 必须是任何类型的公共类型,所以: public post: Post |任何。也许未来的观众可以从中受益,我感谢你们所有人阅读本文!!!

© www.soinside.com 2019 - 2024. All rights reserved.