错误无法分配给类型接口

时间:2017-06-30 17:02:18

标签: angular typescript angular-cli

我正在构建一个角度4应用程序。我创建了一个接口并返回一个类型为interface的服务方法。我在命令提示符下使用ng build命令构建应用程序时,错误无法分配给IMovie []类型。

请参阅下面的屏幕截图以获取更多信息

enter image description here

MovieComponent

import {Injectable} from '@angular/core';
import {MRDBCommonService} from '../shared/services/mrdb.common.service';
import {IMovie} from './movie.interface';
const URL_MOVIE = '/api/movie';

@Injectable()
export class MovieService 
{

constructor(private _mrdbCommonService: MRDBCommonService){}

    getMovies() : IMovie[] {
        return[
         {
            "movieId" : 1,
            "name" : "Titanic",
            "actor" : "Test1",
            "director" : "Test2",
            "movieLength" : 2 
         },
         {
            "movieId" : 2,
            "name" : "Top Gun",
            "actor" : "Test3",
            "director" : "Test4",
            "movieLength" : 2  
         },
         {
            "movieId" : 3,
            "name" : "Moloun Rouge",
            "actor" : "Test5",
            "director" : "Test5",
            "movieLength" : 2  
         }
        ];
    }

    createMovie(){

    }

    deleteMovie(){

    }

}

电影界面

export interface IMovie{

    movieId : number;
    name : string;
    actor : string;
    director : string;
    movieLength : number;  
}

1 个答案:

答案 0 :(得分:0)

删除属性周围的引号字符",然后再次尝试运行ng build,看看错误是否消失。当对象结构与接口定义匹配时,接口完全可以使用。

UPDATE:请务必从接口属性键中删除任何额外的空白字符,否则编译器可能无法识别属性名称导致构建错误。

import { Injectable } from '@angular/core';
import { MRDBCommonService } from '../shared/services/mrdb.common.service';
import { IMovie } from './movie.interface';
const URL_MOVIE = '/api/movie';

@Injectable()
export class MovieService {

    constructor(private _mrdbCommonService: MRDBCommonService) { }

    getMovies(): IMovie[] {
        return [
            {
                movieId: 1,
                name: "Titanic",
                actor: "Test1",
                director: "Test2",
                movieLength: 2
            },
            {
                movieId: 2,
                name: "Top Gun",
                actor: "Test3",
                director: "Test4",
                movieLength: 2
            },
            {
                movieId: 3,
                name: "Moloun Rouge",
                actor: "Test5",
                director: "Test5",
                movieLength: 2
            }
        ];
    }

}

希望这有帮助!