2017-05-26 15 views
0

を提出します。Javascriptの角度は、私がAngular4プロジェクトに取り組んでいると私は、私は現在、私の<strong>app.component.html</strong>に使用しています私の<strong>app.component.ts</strong>にフィルタを作成している

<button (click)="filterBy('cars')">Cars</button> 

これは私が私のnav.component.htmlにこの同じフィルタを使用したいが、私はnav.component.tsに再びフィルタコードを再作成を回避したいのですが、このファイルに正常に動作します

は私のnav.component.htmlからapp.component.tsにこのフィルタを使用する方法はありますか?

+0

このルックスパイプの良いユースケースのように。 – estus

答えて

2

"filter.service.ts"などのサービスを作成できます。 。サービスの良いことは、インスタンスを1つだけ作成することです。だからあなたは、より少ないメモリを使用し、アプリはより高速です。

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> 
+0

サービス用の新しいファイルを作成し、関連するコードをapp.component.tsから削除する必要がありますか? – dj2017

+0

、 'filterBy'メソッドをサービスに移動する必要があります。 – Lazyexpert

+0

メソッドの値を抽出する必要がある場合は、コンポーネントで "this.filter.filterBy"を呼び出すメソッドを作成し、必要な値を返します。 – Lazyexpert

3

作成したフィルタコードを新しい.tsファイルに移行します。 file.ts構文からimport {ClassName}を使用してこのファイルをapp.componentや他のコンポーネントにインポートし、コンポーネントhtmlコードに簡単に実装します。

2
@Injectable() 
export class Service{ 
    //create all the logic here for all the things you want to be shared across compponents 
} 

call this in the component you want to use like 

import {Service} from "../shared/service"; 

@Component({ 
    selector: 'app-angular4' 
}) 
export class Angular4Component implements OnInit { 
    constructor(private service:Service) { 

// resuse all the methods 
} 
+0

これは、複数のコンポーネントで使用されるサービスを使用する場合に使用する角度DIを使用しているので、以下の答えとは異なります –

関連する問題