首页 > 解决方案 > 我的 service.ts 没有在我的组件中调用?

问题描述

在我的 Angular 项目中,我有一个 home 组件。在那个组件中,我有一个方法。所以我有一个 service.ts 并将该服务导入到我的 homecomponent.ts 文件中。我在 service.ts 文件中有一个类似 fliterclicked 和条件的方法。但是在运行时,当我单击该方法时出现此错误 - 'fliterclicked' 不是函数

主页组件.html:

<button (click)="filterClicked()"
        [class.active]="filterChanged"
        id="filterDropdown" type="button"
        class="dropdown-toggle btn btn-clear-default job-filter"></button>

homecomponent.ts:

import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { FilterService } from "../../services/filter.service";
@Component({
  selector: 'jobs-sub-header',
  templateUrl: './sub-header.component.html',
  providers:  [ FilterService ]
})
export class SubHeaderComponent implements OnInit {
constructor(
    private filterService: FilterService) {
}

我的服务.ts:

import {Injectable} from '@angular/core';
@Injectable({
  providedIn: 'root'
})
export class FilterService {
   filterClicked(){
      this.filterShow = !this.filterShow;
   }
 }

我不知道我错过了哪里......请有人帮我解决这个问题吗?

标签: typescriptangular8

解决方案


从 html 直接调用 filterClicked() 只会检查您的组件方法。filterService.filterService()因此,您必须像在 Homecomponent.html 中一样提及它。在您的 ts 构造函数中公开您的服务。

主页组件.ts

constructor(
    public filterService: FilterService) {
}

主页组件.html:

<button (click)="filterService.filterClicked()"
        [class.active]="filterChanged"
        id="filterDropdown" type="button"
        class="dropdown-toggle btn btn-clear-default job-filter"></button>

推荐阅读