我现在在做一个添加course页面,此时我在component.ts ,采用了template来写,
可以实现,但是当我尝试新建一个service.ts,发现提示一堆错误,错误说没有provider,但是我已经写了,貌似是service那里没有返回成功。剩下三幅图分别显示course.html,courese.component.还有service.ts.新手求指导
如图所示
html代码
<h2>{{title}}</h2>
<ul>
<li *ngFor=" let course of courseList ">
{{course}}
</li>
</ul>
<div>
<label>Course Name:</label> <input #courseName />
<button (click)="add(courseName.value); courseName.value=''">
Add
</button>
</div>
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);
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…