对于这个项目,我已经创建了一个类,并且尝试对项目中的某些内容使用构造函数格式。
我的Angular类-
import {Languages} from './temp-languages.enum';
export class Snippet {
private _title: string;
private _desc: string;
private _code: string;
private _lang: Languages;
get title(): string {
return this._title;
}
get desc(): string {
return this._desc;
}
get code(): string {
return this._code;
}
get lang(): Languages {
return this._lang;
}
constructor(title: string, desc: string, code: string, lang: Languages) {
this._title = title;
this._desc = desc;
this._code = code;
this._lang = lang;
}
}
当我尝试在homepage-controller.ts中使用该类时,出现错误,指出它预期有4个参数,但有7个参数。
import { Component, OnInit } from '@angular/core';
import { Snippet } from '../models/snippet';
import { Languages } from '../models/temp-languages.enum';
@Component({
selector: 'app-home-page-controller',
templateUrl: './home-page-controller.component.html',
styleUrls: ['./home-page-controller.component.scss']
})
export class HomePageControllerComponent implements OnInit {
snippets = [
new Snippet(title: 'My Title', desc: 'This is a short description', code: 'there is a small example here', Languages.css)
];
constructor() { }
ngOnInit() {
}
}
我的终端机也出现以下错误-
ERROR in src/app/home-page/home-page-controller/home-page-controller.component.ts(13,22): error TS1005: ',' expected.
src/app/home-page/home-page-controller/home-page-controller.component.ts(13,32): error TS1005: ',' expected.
src/app/home-page/home-page-controller/home-page-controller.component.ts(13,42): error TS1005: ',' expected.
ℹ 「wdm」: Failed to compile.
据我所见,一切都应该正常工作,而且我似乎不明白为什么类构造函数会在数组中引发错误。任何反馈都非常感谢!
答案 0 :(得分:2)
终端错误来自Snippet构造函数中的命名参数。
将title: 'My Title'
更改为'My Title'
,依此类推。
答案 1 :(得分:2)
实例化新对象的方式是错误的-
替换
new Snippet(title: 'My Title', desc: 'This is a short description', code: 'there is a small example here', Languages.css)
作者
new Snippet('My Title', 'This is a short description', 'there is a small example here', Languages.css)
答案 2 :(得分:2)
您已经使用4个参数设置了constructu,但是随后使用诸如结构的对象调用了新的代码段。
使用以下内容:
snippets = [
new Snippet('My Title', 'This is a short description',
'there is a small example here', Languages.css)
];