我正在关注Udemy-Angular 2 with TypeScript for Beginners上的一门课程,并遇到了一个对我而言对于服务不那么明显的错误。Angular2:无法从服务类别中找到不同的支持对象
我有一个组件帽子正在显示一个课程列表。或者是一个字符串数组列表。
由于课程暗示在现实生活中,您不会得到硬编码的项目列表来显示,但会调用某些服务以检索它。该示例调用另一个服务类来检索它(现在在这个类是它返回一个硬编码列表)
我有一个服务类叫做CourseService返回一个字符串数组:
export class CourseService {
getCourses() : string[] {
return ["Course1", "Course2", "Course3"];
}
}
我的组件有一个使用* ngFor的模板循环遍历一个名为courses的局部变量。课程变量被使用依赖注入的构造从服务类获取数组实例:
import {Component} from 'angular2/core'
import {CourseService} from './course.service'
@Component({
selector: 'courses',
template: `
<h2>Courses</h2>
{{ title }}
<ul>
<li *ngFor="#course of courses">
{{ course }}
</li>
</ul>
`,
providers: [CourseService]
})
export class CoursesComponent{
title: string = "The titles of courses page"
courses;
constructor(courseService:CourseService) {
//if i get the courses array from the courseService I get the following error in the browser
/*angular2.dev.js:23083 EXCEPTION: Cannot find a differ supporting object 'function() {
return ["Course1", "Course2", "Course3"];
}' in [courses in [email protected]:16]
I cannot see what is wrong at line 4 in CoursesComponent as it is returning the same string*/
this.courses = courseService.getCourses;
//If I comment out the above line of codeand don't fetch the courses from the service but from a new array it works.
//this.courses = ["Course1", "Course2", "Course3"];
}
}
当我运行这个例子课程不显示,我得到以下错误在控制台:
该类只是返回一个字符串数组。如果我用一个硬编码的字符串[]清除了所有的工作并正确显示。
不确定实际的类或依赖注入是否存在问题。我想,因为它抱怨的是类和线4,它实际上实例化并使用了类。
不过,我认为这是我有我的代码,我收到以下错误:函数返回字符串[]和我的变量是字符串[]。为什么此冲突:
这不是很好。有人告诉你答案,你自己回答。 =(https://stackoverflow.com/a/41388821/124486 –
@EvanCarroll请看看时间戳,以及何时编辑回答以及在离开此类评论前如何编辑它们;)(https://stackoverflow.com/文章/ 41388821 /修订版) – Chrispie