Angular 2 : Cannot find a differ supporting object from service class

标签 angular typescript service

我正在学习 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)没有显示,我在控制台中收到以下错误:

enter image description here

该类只是返回一个字符串数组。如果我用硬编码的字符串 [] 替换掉那个 fetch,一切正常并正确显示。

不确定是实际类有问题还是依赖注入(inject)有问题。我想因为它在提示类和第 4 行,所以它实际上实例化并使用了类。

根据 @5313M 建议,使用 this 会产生以下结果: enter image description here

但是我看到,当我有我的代码时,我收到以下错误:函数正在返回字符串[],我的变量是字符串[]。为什么会出现这种冲突: enter image description here

最佳答案

将其更改为:

this.courses = courseService.getCourses();

关于 Angular 2 : Cannot find a differ supporting object from service class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41388773/

相关文章:

javascript - Angular2,设置超时变量更改后 View 不更新

c# - 用于开发和生产的 .NET Core API 条件身份验证属性

javascript - 编写可调用对象的 typescript

javascript - 无法在 Controller 中使用angularjs服务返回的数据

angular - 如何以 HTMLInputElement 作为参数对 Angular 方法进行单元测试?

javascript - 导入后如何使用全局模块?

reactjs - TypeScript 提示我的 setState 语句使用了属性访问器

c# - Windows服务自动启动和停止,异常处理问题

android - onTaskRemoved() 在华为和小米设备中没有被调用

angular - Nginx:带有 Web 组件的 Angular 应用程序 - 脚本类型 ="module"错误