简体   繁体   English

类型 Angular 上不存在属性

[英]Property does not exist on type Angular

I have an error about property who doesn't exist on type Post[].我有一个关于 Post[] 类型上不存在的属性的错误。 All code works perfectly, but I have this errors in my console.所有代码都运行良好,但我的控制台中有此错误。

在此处输入图像描述

Service.ts服务.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);
      }
    );
  }

Interface界面

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

It is a TS Lint error.这是一个 TS Lint 错误。 The correct way to solve it would be define the corresponding types.解决它的正确方法是定义相应的类型。 Another way to avoid it would be to use bracket notation instead of dot notation.另一种避免它的方法是使用括号表示法而不是点表示法。 Find more details on property accessors here .此处查找有关属性访问器的更多详细信息。

Try the following尝试以下

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

Simply you can fix this error If you don't care about typing, by adding:any如果您不关心打字,只需添加:any

 (res : any) => {

But, the best practice is to have those types defined in your domain models.但是,最佳实践是在您的领域模型中定义这些类型。 You can replace:any with the type you defined.你可以用你定义的类型替换:any。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM