我现在在做一个添加course页面,此时我在component.ts ,采用了template来写,
可以实现,但是当我尝试新建一个service.ts,发现提示一堆错误,错误说没有provider,但是我已经写了,貌似是service那里没有返回成功。剩下三幅图分别显示course.html,courese.component.还有service.ts.新手求指导
如图所示

html代码
{{title}}
-
{{course}}
component.ts部分代码
import { Component, OnInit } from '@angular/core';
import {CoursesService} from '../courses.service';
import {AutoGrowDirective} from '../auto-grow.directive';
@Component({
selector: 'app-courses',
templateUrl: './courses.component.html',
styleUrls: ['./courses.component.css'],
providers:[CoursesService]
})
export class CoursesComponent implements OnInit {
title="The title of courses page";
//courses;
courseList;
//courseName;
constructor( CoursesService:CoursesService) {
this.courseList=CoursesService.getCourses();
//this.courseList=CoursesService.savecourse();
// this.courseName=CoursesService.onKey();
}
ngOnInit() {
}
}
service.ts
import { Injectable } from '@angular/core';
@Injectable()
export class CoursesService {
courseName:string;
courseList:string[] = ["Course1","Course2","Course3"];
constructor(courseList:string[]) {
this.courseList = courseList.concat(this.courseList);
}
getCourses():string[] {
return this.courseList;
}
savecourse(courseName){
//alert(this.courseName);
this.courseList.push(courseName);
//console.log(courseNameInput);
}
onKey(e){
this.courseName += e.key;
console.log(this.courseName);
}
}
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
因为你的Service是一个带有参数的构造方法,所以DI无法确认值应该多少,为了让DI正常实例化,可以加上
@Optional()来表示参数可选项。