首页 > 解决方案 > Angular 类型不存在属性

问题描述

我有一个关于 Post[] 类型上不存在的属性的错误。所有代码都运行良好,但我的控制台中有此错误。

在此处输入图像描述

服务.ts

  private objectAllPosts: BehaviorSubject<Post[]>;
  public allPosts: Observable<Post[]>;
  private listPosts: Post[] = [];
  public tempPosts: Post[] = [];

  constructor(private _http: HttpClient, private _toast: ToastService) {
    this.objectAllPosts = new BehaviorSubject(null) as BehaviorSubject<Post[]>;
    this.allPosts = this.objectAllPosts.asObservable();
  }

  public getAllPosts() {
    this._http.get<Post[]>(environment.apiUrl + "/api/posts/").subscribe(
      (res) => {
        this.listPosts = res.posts;                 // MESSAGE ERROR
        this.tempPosts = [...res.posts];            // MESSAGE ERROR
        this.objectAllPosts.next(this.listPosts);   // MESSAGE ERROR
      },
      (error) => {
        console.log(error);
      }
    );
  }

界面

export class Post {
  public _id?: string;
  public post: string;
  public posts: [];
  public comments?: object;
  public createdAt?: object;
}

标签: angularinterfacerxjs

解决方案


这是一个 TS Lint 错误。解决它的正确方法是定义相应的类型。另一种避免它的方法是使用括号表示法而不是点表示法。在此处查找有关属性访问器的更多详细信息。

尝试以下

this.listPosts = res['posts'];
this.tempPosts = [...res['posts']];

推荐阅读