Dependency injection

Both the @Component and @Directive decorators offer a factory option giving you the ability to run your own function to create an instance of the class behind them.

There are many use-case where this option can be useful, but the one we will see here is dependency injection. Here is an example of how it could be done:

import { Injector, Module, Inject } from "@banquette/dependency-injection";
import { HttpService } from "@banquette/http";
import { Prop } from '@banquette/vue-typescript';

@Module() // We declare that the class is a module.
@Component({ // We declare that is also a component.
    name: 'user-profile',

    // We define a function resposible for creating the instace.
    // Here we call the injector that will create the module instance.
    factory: () => Injector.Get(UserProfile)
})
class UserProfile {
    @Prop({type: String, required: true}) public id: string;

    @Expose() public httpResponse!: HttpResponse<any>;

    // Now we can inject any dependency we want.
    public constructor(@Inject(HttpService) private http: HttpService) { }

    public mounted(): void {
        this.httpResponse = this.http.get(`/user/${this.id}`);
    }
}