【发布时间】:2021-01-28 08:20:26
【问题描述】:
我正在学习Udemy-Angular 2 with TypeScript for Beginners 上的课程,但遇到了一个对我来说在服务方面并不明显的错误。
我有一个组件帽子正在显示课程列表。或字符串数组列表。
正如课程所暗示的那样,在现实生活中,您不会得到要显示的硬编码项目列表,而是会调用一些服务来检索它。该示例调用另一个服务类来检索它(现在在这个类中它是一个硬编码的列表,它会返回)
我有一个名为 CourseService 的服务类,它返回一个字符串数组:
export class CourseService {
getCourses() : string[] {
return ["Course1", "Course2", "Course3"];
}
}
我的组件有一个模板,它使用 *ngFor 来循环一个名为 course 的局部变量。通过在构造函数中使用依赖注入从服务类中获取数组来实例化课程变量:
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"];
}
}
当我运行此示例时,课程不显示,并且我在控制台中收到以下错误:
该类只是返回一个字符串数组。如果我用硬编码的字符串 [] 删除该提取,所有工作都可以正常显示。
不确定实际类或依赖注入是否存在问题。我想既然它在抱怨类和第 4 行,它实际上确实实例化并使用了类。
【问题讨论】:
标签: angular typescript service