angulart接口错误:不能分配给类型

时间:2018-03-11 19:07:06

标签: angular interface

当我尝试使用一个界面并且我不知道为什么时,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'};
 }
}

2 个答案:

答案 0 :(得分:1)

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

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

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

这是你创建对象的方法

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

答案 1 :(得分:0)

尝试以下方法:

在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?