angular - 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>
解决方案
问题似乎出在您的 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 的信息在这里
推荐阅读
- c# - 在 C# 中处理事件时消息框不会显示
- android - Firebase 身份验证不会在签名的 apk 中发送 otp
- python - Python, Youtube-video-downloader-merger 我可以让这个脚本运行得更快吗?
- fancybox-3 - 你如何防止花哨的盒子的关闭按钮自动隐藏?
- .net - 如何显示 NuGet 包依赖项?
- ios - 无法使用 Core Data 和 Swift 在表格视图中正确保存和显示数据
- javascript - 用过滤器代替接头
- sql - 在表 Sql Server 中创建多个编号的行
- android - 在 kotlin 中使用 itext5 将表格添加到现有 PDF
- html - 在 NavBar 中间定位 Logo