Angular:如何将字符串发送到注射服务?

问题描述 投票:4回答:3

我创建了通用服务到crud任务,服务使用HttpClient通过DI(依赖注入),但我需要在服务的构造函数中通知另一个值,如何制作这个?

因为当我在我的类的构造函数中定义将使用DI消耗CRUD服务时,没有办法将参数传递给构造函数

以下是服务

import { Injectable } from "@angular/core";
import { HttpClient } from "@angular/common/http";
import { CrudInterface } from "@app/core/crud.interface";
import { environment } from "@env/environment";
import { Observable } from "rxjs/Observable";

@Injectable()
export class CRUD<T> implements CrudInterface<T>{
    
    endpoint: string;

    constructor(private http: HttpClient, routeDir: string){
        this.endpoint = `${environment.endpoint}/${routeDir}`;
    }
    
    getAll(): Observable<T[]> {
        return this.http.get<T[]>(`${this.endpoint}`);
    }

    get(id: number): Observable<T> {
        return this.http.get<T>(`${this.endpoint}/${id}`);
    }

    create(object: T): Observable<T> {
        return this.http.post<T>(`${this.endpoint}`, object);
    }

    update(object: T): Observable<T> {
        return this.http.put<T>(`${this.endpoint}`, object);
    }

    delete(id: number): Observable<any> {
        return this.http.delete<T>(`${this.endpoint}/${id}`);
    }

}

import { Usuario } from "@app/usuarios/model/usuario";
import { CRUD } from "@app/core/crud.service";

class TestCrudServide {

    constructor(
        /**
         * How to inform the parameter here?
         * in this case the endpoint (2nd parameter of the CRUD service)
         */
        private crudService: CRUD<Usuario>
    ){ }

    getAll(){
        this.crudService.getAll();
    }
}

UPDATE

利用SannonAragão(感谢)提出的工厂概念解决方案,我创建了动态创建实例的服务提供程序

https://angular.io/guide/dependency-injection#factory-providers

export class crudServiceProvider {

    static getProvider(routeDir: string) {
        return {
            provide: CRUD,
            deps: [HttpClient],
            useFactory: (dep) => {
                return new CRUD(dep, routeDir);
            }
        }
    }
}

在我的组件中

@Component({
  selector: 'app-revenda',
  templateUrl: './revenda.component.html',
  styleUrls: ['./revenda.component.css'],
  providers:[ crudServiceProvider.getProvider('/api/revenda') ]
})
export class RevendaComponent implements OnInit {

  constructor(
      private crudService: CRUD<Revenda>
    ) { }
    
    ngOnInit() {
      // now it's work with the correct path and type!
      this.crudService.get(1).subscribe(item => console.log(item));
    }
}
angular dependency-injection dependencies code-injection
3个回答
3
投票

Filipe,来自您希望提供服务的模块:

{
provide: 'userService1',
deps: [ HttpClient ],
useFactory: (dep1 ) => {
    return new UserService( dep1, 'test');
  }
}

在您将使用该服务的组件中:

constructor( @Inject('userService1') private userService: UserService ) { }

在CRUD API中,您将参数作为字符串获取:

constructor( private http: HttpClient, private s: string) {
  console.log(s); // will print 'test'
}

1
投票

我不相信你可以通过依赖注入如何工作来做到这一点。你可以做的是创建一个基础CRUD类

export class CRUD<T> implements CrudInterface<T>{

    endpoint: string;

    constructor(private http: HttpClient, routeDir: string){
        this.endpoint = `${environment.endpoint}/${routeDir}`;
    }

    getAll(): Observable<T[]> {
        return this.http.get<T[]>(`${this.endpoint}`);
    }

    get(id: number): Observable<T> {
        return this.http.get<T>(`${this.endpoint}/${id}`);
    }

    create(object: T): Observable<T> {
        return this.http.post<T>(`${this.endpoint}`, object);
    }

    update(object: T): Observable<T> {
        return this.http.put<T>(`${this.endpoint}`, object);
    }

    delete(id: number): Observable<any> {
        return this.http.delete<T>(`${this.endpoint}/${id}`);
    }

}

然后创建一个扩展CRUD类的Injectable服务

@Injectable()
export class UserService extends CRUD<Usario> {
    constructor(http: HttpClient){
        super(http, 'users');
    }
}

UserService是您在AppModule中提供的类并注入到组件中。你可以看到super被用来传入routeDir参数。这是一个stack blitz演示这个。


0
投票

你不能在构造函数中实现任何东西。你必须注入httpservice对象(crudservice),你必须将参数传递给函数。

要实现第二个,你必须做这样的事情

this.crudService.get(10);

© www.soinside.com 2019 - 2024. All rights reserved.