Angular2:无法从服务类

时间:2016-12-29 23:47:08

标签: angular typescript service

我正在关注Udemy-Angular 2 with TypeScript for Beginners的课程,并遇到了一个对我来说不是那么明显的错误。

我有一个组件帽子正在显示课程列表。或者字符串数组列表。

由于课程暗示在现实生活中你不会得到要显示的硬编码项目列表,但会调用某些服务以便检索它。该示例调用另一个服务类来检索它(现在在这个类中它是一个它返回的硬编码列表)

我有一个名为CourseService的服务类,它返回一个字符串数组:

export class CourseService {
    getCourses() : string[] {        
        return ["Course1", "Course2", "Course3"];
    }

}

我的组件有一个模板,使用* ngFor来循环一个名为courses的局部变量。 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"];
    }
}

当我运行此示例时,课程不显示,我在控制台中收到以下错误:

enter image description here

该类只是返回一个字符串数组。如果我使用硬编码字符串[]进行提取,则所有工作都能正常显示。

不确定实际类或依赖项注入是否存在问题。我想,因为它抱怨类和第4行它确实实例化并使用了类。

根据@ 5313M使用此建议,导致以下结果: enter image description here

但是我看到,因为我有我的代码,我收到以下错误:函数返回string [],我的变量是字符串[]。为什么会发生冲突: enter image description here

4 个答案:

答案 0 :(得分:3)

将其更改为:

this.courses = courseService.getCourses();

答案 1 :(得分:0)

请用下面的代码替换您的代码并尝试:

 <li *ngFor='let course of courses'>
            {{ course }}
</li>
courses : string[];
this.courses = this.courseService.getCourses();

答案 2 :(得分:0)

非常愚蠢的问题。会教我不要使用intellisense / autocomplete。

根据课程建议,我们应该使用vs编辑器。不确定它是编辑器还是角度-2,但是如果你去了courseService。和Ctrl + Space以完成它并选择它完成方法但不在方法调用上添加()的方法。

因此我有:

this.courses = courseService.getCourses; 

而不是:

this.courses = courseService.getCourses();

答案 3 :(得分:0)

this.courses = courseService.getCourses;

您没有在方法调用中放置括号:

this.courses = courseService.getCourses();