Javascript使用来自不同.ts文件的代码
我正在从事一个Angular4项目,我在我的app.component.ts上创建了一个过滤器,我目前正在app.component.html上使用该过滤器Javascript使用来自不同.ts文件的代码,javascript,angular,Javascript,Angular,我正在从事一个Angular4项目,我在我的app.component.ts上创建了一个过滤器,我目前正在app.component.html上使用该过滤器 <button (click)="filterBy('cars')">Cars</button> 汽车 这在这个文件中工作得很好,因为我想在我的nav.component.html上使用相同的过滤器,但我想避免在nav.component.ts上重新创建过滤器代码 <button (click)="filt
<button (click)="filterBy('cars')">Cars</button>
汽车
这在这个文件中工作得很好,因为我想在我的nav.component.html上使用相同的过滤器,但我想避免在nav.component.ts上重新创建过滤器代码
<button (click)="filterBy('cars')">Cars</button>
有没有办法在我的app.component.ts中的nav.component.html上使用此筛选器?将创建的筛选器代码迁移到新的.ts文件中。使用Import{ClassName}from file.ts语法在app.component和其他组件中导入此文件,然后在组件html代码中轻松实现它将创建的筛选代码迁移到一些新的.ts文件中。使用Import{ClassName}from file.ts语法在app.component和其他组件中导入此文件,然后在组件html代码中轻松实现它您可以创建服务,例如“filter.service.ts”。服务中的优点是——它只会创建一个实例。所以你们使用更少的内存,应用程序更快。 然后-您可以将其包括到父模块中:
import { FilterService } from "some/filter.service.ts";
@NgModule({
declarations: [ AppComponent, NavComponent],
providers: [ FilterService ]
})
export class MyModule { }
并在您的组件中使用,如下所示:
import { FilterService } from "some/filter.service.ts";
constructor(filter: FilterService) {
this.filter = filter;
}
然后是您的html:
<button (click)="filter.filterBy('cars')">Cars</button>
汽车
您可以创建服务,例如“filter.service.ts”。服务中的优点是——它只会创建一个实例。所以你们使用更少的内存,应用程序更快。
然后-您可以将其包括到父模块中:
import { FilterService } from "some/filter.service.ts";
@NgModule({
declarations: [ AppComponent, NavComponent],
providers: [ FilterService ]
})
export class MyModule { }
并在您的组件中使用,如下所示:
import { FilterService } from "some/filter.service.ts";
constructor(filter: FilterService) {
this.filter = filter;
}
然后是您的html:
<button (click)="filter.filterBy('cars')">Cars</button>
汽车
这看起来是管道的一个很好的用例。这看起来是管道的一个很好的用例。我是否需要为该服务创建一个新文件,并从app.component.ts中取出相关代码?当然,应该将方法“filterBy”移到该服务中。如果需要提取该方法的某些值,请在组件中创建另一个方法,调用“this.filter.filterBy”,这将返回您需要的值。我是否需要为该服务创建一个新文件并从app.component.ts中取出相关代码?当然,应该将方法“filterBy”移动到该服务。如果您需要提取该方法的某些值,请在组件中创建另一个方法,该方法调用“这个。过滤器。过滤器比“,这将返回您需要的值。这与下面的答案不同,因为我们在使用多个组件中使用的服务时应使用角度DI。这与下面的答案不同,因为我们在使用多个组件中使用的服务时应使用角度DI