Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
730 views
in Technique[技术] by (71.8m points)

angular2 提示No provider for Array!

我现在在做一个添加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);
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

因为你的Service是一个带有参数的构造方法,所以DI无法确认值应该多少,为了让DI正常实例化,可以加上 @Optional() 来表示参数可选项。

constructor(@Optional() courseList:string[]) {
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...