首页 > 解决方案 > 类型错误:_co.function 不是函数

问题描述

我正在使用 angular 并尝试在我的本地主机上创建一个网页,但我无法使用函数。我认为这是一个路径问题,但我已经正确声明了所有路径。

花了 4 个小时试图用谷歌搜索答案,没有找到任何答案。

我自己创建了 2 个组件,在我创建 Angular 项目时由 defualt 制作的组件之外:

post-create.component.html

创建后.component.ts

在 app 文件夹中,它们都位于:

'./posts/posts-create/post-create.component.html'
'./posts/posts-create/post-create.component.ts'

我一直在复制粘贴文件夹名称以确保它不是拼写错误

post-create.component.ts 看起来像这样:

import { Component } from '@angular/core';


@Component({
  selector: 'app-post-create',
  templateUrl: './post-create.component.html'
})
export class PostCreateComponent{
  newPost = '';

  onAddPost(){
    this.newPost = 'The users posts';
  }
}

post-create.component.html 只是填充了一些随机的东西来让它工作,但看起来像这样:

<h2> sup </h2>

我的 app.component.html 是:

<h1> Hello world </h1>
<textarea rows="6"></textarea>
<hr>
<button (click)="onAddPost()"> Save post </button>
<p>{{ newPost }}</p>

这应该在单击按钮时调用函数“onAddPost()”但不会。它给出了这个错误: ERROR TypeError: _co.onAddPost is not a function

我不知道为什么。我的 app.module.ts 文件是这样的:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { PostCreateComponent } from './posts/posts-create/post-create.component'

@NgModule({
  declarations: [
    AppComponent,
    PostCreateComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

如您所见,我已导入 import { PostCreateComponent } from './posts/posts-create/post-create.component' 并将其添加到声明中

该代码是我正在观看的视频的一部分,只是为了进入它而编写代码。如果你更喜欢它来自这个视频: https ://www.youtube.com/watch?v=1tRLveSyNz8&fbclid=IwAR0k3FKxqbYVKuT3g2UgJVQWFW2xFXV8xmhzGbwqbyZ3ltWrBcVktYc38_I

提前感谢您的回答,很抱歉占用您的时间,我已尝试自己解决此问题,但似乎无法找出为什么它不允许我使用该功能

标签: javascriptangulartypescriptmean-stack

解决方案


再次观看1:02:00的视频:

以下内容与 post-create.component.ts 相关(与 app.component.ts 无关):

<h1> Hello world </h1>
<textarea rows="6"></textarea>
<hr>
<button (click)="onAddPost()"> Save post </button>
<p>{{ newPost }}</p>

推荐阅读