Angular2 access global service without including it in every constructor

后端 未结 2 656
Happy的楠姐
Happy的楠姐 2021-01-06 22:38

I have three classes:

@Injectable()
export class ApiService {
  constructor(public http: Http) {}

  get(url: string) {
    return http.get(url);
  }

}

@In         


        
2条回答
  •  Happy的楠姐
    2021-01-06 23:13

    If you want to get it passed in by DI you have to use the constructor. Constructors are not inherited therefore you need to implement the constructor in each and every subclass and pass arguments to the superclass constructor by calling super(arguments). The only exception are default constructors without any arguments which are kinda autogenerated.

    What you could do is to inject Injector and pass it forward to the superclass where the superclass requests Http from the Injector imperatively. This might be a bit of an advantage if you inject multiple services because you only have to declare one constructor argument but in my opinion this makes it harder to reason about the code.

提交回复
热议问题