typescript Angular 2:不是一个函数,但它存在
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40708944/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Angular 2: is not a function but it exist
提问by Nick Alexander
I am trying to get an array out of a different class but he says the function does not exist. here is my code:
我试图从不同的类中获取数组,但他说该函数不存在。这是我的代码:
courses.component.ts:
course.component.ts:
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 = "The title of courses page";
courses;
constructor(courseService: CourseService){
this.courses = CourseService.getCourses();
}
}
course.service.ts:
course.service.ts:
export class CourseService{
getCourses() : string[]{
return ["Course1","Course2","Course3"];
}
}
回答by Günter Z?chbauer
You need to reference the argument name, not the argument type
您需要引用参数名称,而不是参数类型
this.courses = courseService.getCourses();
^ lower case c
回答by Diego
I think it's some kind of bug, because TypeScript recognize me the method but when I delete and type the method again getCourses() in the component, it says that the method is not found, then I go to the Service and start to delete blank lines, and the method Works. I'm currently using Angular 4
我认为这是某种错误,因为TypeScript识别了我的方法但是当我在组件中删除并再次键入getCourses()方法时,它说找不到该方法,然后我转到Service并开始删除空白行,和方法 Works。我目前正在使用 Angular 4
回答by DavGarcia
I had the same inexplicable problem. I copy and pasted the code from the web and something must not have been right in the function declaration. I deleted the line
我有同样的莫名其妙的问题。我从网上复制并粘贴了代码,函数声明中一定有什么不对的地方。我删除了该行
getCourses(): string[] {
getCourses(): string[] {
and typed it out again by hand. When I ran the code, it worked. Maybe some invisible character was pasted in and messing up Typescript? Who knows.
并再次手动输入。当我运行代码时,它起作用了。也许一些隐形字符被粘贴进来并弄乱了打字稿?谁知道。