我正在学习 Udemy-Angular 2 with TypeScript for Beginners 的类(class)并遇到了一个对我来说不是很明显的服务错误。
我有一个组件帽子显示类(class)列表。或字符串数组列表。
正如本类(class)所暗示的那样,在现实生活中您不会获得要显示的硬编码项目列表,而是会调用某些服务来检索它。该示例调用另一个服务类来检索它(目前在此类中它是一个返回的硬编码列表)
我有一个名为 CourseService 的服务类,它返回一个字符串数组:
export class CourseService {
getCourses() : string[] {
return ["Course1", "Course2", "Course3"];
}
}
我的组件有一个模板,它使用 *ngFor 循环遍历名为 courses 的局部变量。通过在构造函数中使用依赖注入(inject)从服务类中获取数组来实例化类(class)变量:
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 CoursesComponent@4: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"];
}
}
当我运行这个例子时,类(class)没有显示,我在控制台中收到以下错误:
该类只是返回一个字符串数组。如果我用硬编码的字符串 [] 替换掉那个 fetch,一切正常并正确显示。
不确定是实际类有问题还是依赖注入(inject)有问题。我想因为它在提示类和第 4 行,所以它实际上实例化并使用了类。
最佳答案
将其更改为:
this.courses = courseService.getCourses();
关于 Angular 2 : Cannot find a differ supporting object from service class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41388773/