Angular:如何将字符串发送到注入(inject)服务?

标签 angular dependency-injection dependencies code-injection

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

因为当我在类的构造函数中定义将使用 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();
    }
}

更新

利用 Sannon Aragã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));
    }
}

最佳答案

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'
}

关于Angular:如何将字符串发送到注入(inject)服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48064920/

相关文章:

angular - 如何在 Angular 2 中将多个 Observable 组合在一起

php - SF2 : Configure a service that gives a new object instance each time

php - 包装类和依赖注入(inject)

android - gradle文件中 'com.android.support:appcompat-v7.27.1.1'的问题

dependencies - CMake 和 CTest : make test doesn't build tests

javascript - BehaviorSubject 与 Observable?

angular - RC4 - 无法绑定(bind)到 'routerLink',因为它不是已知的 native 属性

wcf - 具有需要参数的服务的自托管(无 IIS 或 WAS)WCF

automation - 在 Bamboo 中设置依赖关系/触发器?

Angular OnPush : how do I force changes to be detected from outside?