首页 > 解决方案 > TS2551:“PostListComponent”类型上不存在属性“post”

问题描述

我已经阅读了答案,但我被困住了......我正在尝试通过点击操作删除帖子。我已经创建了所有方法,但是当我在 onDeletePost() 方法上添加帖子作为参数时,我的 post-list-component.html 中出现此错误:TS2551:“PostListComponent”类型上不存在属性“post”。您指的是 'posts' 吗? 如果我发布帖子,我还有另一个错误消息(TS2345)......如果您需要更多信息,请告诉我,非常感谢!

这是我的posts.service.ts

import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';
import { Post } from '../models/post.model';

@Injectable()
export class PostsService {


  posts : Post[] = [];
  postsSubject = new Subject<any[]>();

  emitPosts() {
      this.postsSubject.next(this.posts);
    }

  createNewPost(newPost : Post) {
    this.posts.push(newPost);
    this.emitPosts();
  }

  removePost(post : Post) {
    const postIndexToRemove = this.posts.findIndex(
      (postEl) => {
        if(postEl === post) {
          return true;
        } else {
          return ' '
        }
      }
    );
    this.posts.splice(postIndexToRemove, 1);
    this.emitPosts();
  }
}

后列表组件.ts

import { Component, OnInit, Input, Output, OnDestroy } from '@angular/core';
import { Router } from '@angular/router';
import { Subscription } from 'rxjs';
import { Post } from '../models/post.model';
import { PostsService } from '../services/posts.service';


@Component({
  selector: 'app-post-list',
  templateUrl: './post-list.component.html',
  styleUrls: ['./post-list.component.scss']
})
export class PostListComponent implements OnInit, OnDestroy {
  
  posts : Post[];
  postsSubscription: Subscription;

  constructor(private postsService: PostsService,
              private router: Router) { }

  ngOnInit(): void {
    this.postsSubscription = this.postsService.postsSubject.subscribe(
      (posts: Post[]) => {
        this.posts = posts;
      }
    );
    this.postsService.emitPosts()
  }


  onDeletePost(post: Post) {
    this.postsService.removePost(post);
  }

  ngOnDestroy() {
    this.postsSubscription.unsubscribe();
  }
}

和我的 post-list-component.html :


<li class="list-group-item">
  <button class="btn btn-warning" (click)="onDeletePost(post)"> Supprimer </button>
</li>

标签: angulartypescript

解决方案


问题似乎出在您的 html 中,因为正在观看您的代码段。我会将html代码更改为

<ng-container *ngFor="let post of posts">
    <li class="list-group-item">
      <button class="btn btn-warning" (click)="onDeletePost(post)"> Supprimer </button>
    </li>
</ng-container>

是什么导致了错误?

posts基本上,您有一个要在页面中显示的数组。为此,您需要在每个帖子中循环该数组帖子。

*ngFor="let post of posts"

post这样做,为每次迭代创建一个引用。

因此,例如,如果您的帖子数组有 3 个帖子,则ngFor该数组将循环 3 次。

在 ngFor 内部,您现在可以传递post给函数onDeletePost

更多关于 *ngFor 的信息在这里


推荐阅读