【问题标题】:angulart interface error: is not assignable to type角度界面错误:不可分配给类型
【发布时间】:2018-03-11 19:07:06
【问题描述】:

当我尝试使用一个界面时,Angular 告诉我这个错误,我不知道为什么。

file: '*******/movies.component.ts'
severity: 'Error'
message: 'Type '{ title: string; id: string; }' is not assignable to type 
'Movie'.
Property 'consructor' is missing in type '{ title: string; id: string; }'.'
at: '16,9'
source: 'ts'

我有这个界面:

export class Movie{
title : string;
id : string;

consructor(title : string, id: string){
    this.title = title;
    this.id = id;
  }
}

我有这门课

export class MoviesComponent implements OnInit {
movies:Movie;
constructor(){

}
ngOnInit() {
    this.movies = {title: 'ToyStory', id:'134'};
 }
}

【问题讨论】:

    标签: angular interface


    【解决方案1】:

    错字应为constructor(title : string, id: string)

    这是什么语法?这是错误的

    this.movies = {title: 'ToyStory', id:'134'}
    

    这就是你创建对象的方式

     this.movies=new Movie('ToyStory','134');
    

    【讨论】:

      【解决方案2】:

      在下面试试这个:

      在movie.model.ts中:

      export interface IMovie {
          title: string;
          id: string;
      }
      
      export class Movie implements IMovie {
          constructor(
              public title: string,
              public id: string
          ) { }
      }
      

      在movie.component.ts中:

      export class MoviesComponent implements OnInit {
          private _movies: Movie[];
      
          ngOnInit() {
              this._movies.push(new Movie('ToyStory','134'));
          }
      }
      

      为什么要使用字符串作为 id?

      【讨论】:

        猜你喜欢
        • 2020-11-20
        • 2020-06-02
        • 1970-01-01
        • 1970-01-01
        • 2019-02-27
        • 1970-01-01
        • 2018-10-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多