首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Angular 2-如何将参数传递给抽象服务

Angular 2-如何将参数传递给抽象服务
EN

Stack Overflow用户
提问于 2017-01-25 22:01:53
回答 1查看 1.4K关注 0票数 2

Angular 2-当我在模块中提供服务时,如何向抽象服务传递参数

具有抽象服务的文件

代码语言:javascript
运行
复制
@Injectable()
export class Service<T>{
    private headers: RequestOptions = headersRequest.options;
    private readonly baseUrl: string;

    constructor(private http: Http, baseUrl: string) {
        this.baseUrl = baseUrl;
    }

    public getAll(): Promise<T[]> {
        return this.http.get(`${this.baseUrl}`)
            .toPromise()
            .then(this.extractData)
            .catch(this.handleError);
    }

    public get(id: number): Promise<T> {
        return this.http.get(`${this.baseUrl}`)
            .toPromise()
            .then(this.extractData)
            .catch(this.handleError);
    }

    private extractData(res: Response) {
        let body = res.json();
        return body || {};
    }

    private handleError(error: Response | any) {
        let errMsg: string;
        if (error instanceof Response) {
            const body = error.json() || '';
            const err = body.error || JSON.stringify(body);
            errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
        } else {
            errMsg = error.message ? error.message : error.toString();
        }
        console.error(errMsg);
        return Promise.reject(errMsg);
    }
}

当我提供服务时,使用模块的文件

代码语言:javascript
运行
复制
@NgModule({
    imports: [
        SharedModule,
        RouterModule.forChild(routes)
    ],
    declarations: [
        HeaderTennisComponent,
        TennisComponent,
        ProgramsComponent,
        ProgramComponent,
        PlotsComponent,
        GuidesComponent,
        CategoriesComponent,
        ChampionsComponent
    ],
    providers: [Service]
})

当我使用服务时,我会使用组件的文件。

代码语言:javascript
运行
复制
export class ProgramComponent implements OnInit {
    private program: IProgram;
    constructor(private route: ActivatedRoute, private tennisService: Service<IProgram>) {
        //
    }

    public ngOnInit() {
        this.getProgram(+this.route.snapshot.params['id']);
    }

    private getProgram(id: number) {
        this.tennisService.get(id).then(
            (program) => this.program = program
        );
    }
}

当我提供服务时,我需要传递baseUrl。

EN

回答 1

Stack Overflow用户

发布于 2017-01-25 22:15:08

Angular DI不直接支持泛型。

根据您的要求,有几种解决方法:

代码语言:javascript
运行
复制
providers: [
  {provide: 'baseUrl': useValue: 'http://example.com'},
  {provide: Service, useFactory: (http, baseUrl) new Service<IProgram>(http, baseUrl), deps: [Http, new Inject('baseUrl') },
  {provide: 'ServiceIProgram', useFactory: (http, baseUrl) new Service<IProgram>(http, baseUrl), deps: [Http, new Inject('baseUrl') },
  {provide: 'Service', useFactory: (http, baseUrl) => (T) => new Service<T>(http, baseUrl), deps: [Http, new Inject('baseUrl')]
]
代码语言:javascript
运行
复制
@Injectable()
export class Service<T>{

    ...

    constructor(private http: Http, @Inject('baseUrl') baseUrl: string ) {
        this.baseUrl = baseUrl;
    }
代码语言:javascript
运行
复制
export class ProgramComponent implements OnInit {
    ...
    constructor(private route: ActivatedRoute, 
       @Inject(Service) private tennisService: Service<IProgram>, // fixed type parameter
       @Inject('ServiceIProgram') private tennisService: Service<IProgram>,

       @Inject('Service') serviceFactory:any // factory to instantiate yourself
    ) {
        // not sure if passing generic type parameters this way is supported by TypeScript
        this.tennisService = serviceFactory(IProgram);
    }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41853579

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档