angular 2(ng2-completer) - 避免从组件服务中的http依赖注入

时间:2016-10-21 08:51:07

标签: http angular dependency-injection

我为ng2-Completer编写了自定义数据实现。

import {Inject} from "@angular/core";
import {Http, Response} from "@angular/http";
import {Subject} from "rxjs/Subject";

import {CompleterData, CompleterItem} from "ng2-completer";

export class CustomData extends Subject<CompleterItem[]> implements CompleterData {

    constructor(private http: Http) {
        super();
    }
    public search(searchTerm: string): void {
        this.http.get("http://localhost:5002/api/v1/Search?keyword=" + searchTerm)
            .map((res: Response) => {
                let data = res.json();
                let matches: CompleterItem[] = data.map((result: any) => {
                    return {
                        title: result.name,
                        originalObject: result
                    }
                });
                this.next(matches);
            })
            .subscribe();
    }

    public cancel() {
    }
}

在我的组件中,我正在做类似

的事情
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { HomeService } from '../home/home.service';
import { FactoryService } from '../factory/factory.service';
import { SupplierService } from '../supplier/supplier.service';
import { BusinessAreaService } from '../business-area/business-area.service';
import { CustomData } from './custom-data';
import {CompleterData, CompleterItem} from "ng2-completer";
import { SearchItem } from "./search.item";
import { Http } from '@angular/http';


@Component({
    moduleId: module.id,
    templateUrl: "./home.component.html",
    styleUrls: ["./home.component.css"]
})

export class HomeComponent implements OnInit {
    factories: any;
    suppliers: any;
    businessAreas: any;
    private searchStr: string;
    private customData: CustomData;
    errorMessage;

    constructor(private http: Http, private homeService: HomeService, private factoryService: FactoryService, private supplierService: SupplierService, private businessAreaService: BusinessAreaService, private router: Router) {
        this.customData = new CustomData(http);
    }

    ngOnInit(): void {
        this.getAllFactories();
        this.getAllSupplier();
        this.getAllBusinessAreas();
    }
}

有没有办法可以避免组件中的http注入,只有在CustomData中,我是否也需要使自定义数据可注入?

1 个答案:

答案 0 :(得分:0)

@Injectable()课程的顶部添加CustomData,然后将其添加到@NgModule.providers。然后,您只需将CustomData注入组件

@Injectable()
class CustomData {}

@Component({})
class MyComponent {
  constructor(private data: CustomData) {}
}

@NgModule({
  providers: [ CustomData ]
})
class SomeModule {}

这将使整个应用程序中的CustomData实例可用。如果希望每个组件获得CustomData的新实例,请将其添加到@Component.providers而不是

@Component({
  providers: [ CustomData ]
})
class MyComponent {
  constructor(private data: CustomData) {}
}