我可以注入自定义(路径)位置策略吗?
我正在使用自定义 pathlocationstrategy :
@Injectable() // also tried @Injectable({providedIn: 'root'})
export class CustomPathLocationStrategy extends PathLocationStrategy {
constructor() {
console.log('CustomPathLocationStrategy constructor');
}
....
}
让Angular知道我自己在app.module中的实现.TS:
providers: [
{
provide: LocationStrategy,
useClass: CustomPathLocationStrategy
}
这很好。
但是现在,我尝试将CustomPathLocationsty注入一个组件:
@Component(...)
export class AppComponent {
constructor(private custom: CustomPathLocationStrategy) {}
浏览器控制台现在两次打印“ CustomPathLocationStrategy构造函数”消息两次:为CustomPathLocationstategy创建了一个新对象。这与用于实现位置策略的一种不同。
我是否不应该在自己的组件或其他服务中注入CustomPathlocatationgaty?还是我做错了?
I'm using a custom PathLocationStrategy:
@Injectable() // also tried @Injectable({providedIn: 'root'})
export class CustomPathLocationStrategy extends PathLocationStrategy {
constructor() {
console.log('CustomPathLocationStrategy constructor');
}
....
}
To let Angular know about my own implementation in app.module.ts:
providers: [
{
provide: LocationStrategy,
useClass: CustomPathLocationStrategy
}
This is working fine.
But now I try to inject CustomPathLocationStrategy into a component:
@Component(...)
export class AppComponent {
constructor(private custom: CustomPathLocationStrategy) {}
The browser console now prints the "CustomPathLocationStrategy constructor" message twice: a new object is created for CustomPathLocationStrategy. This one is different from the one that is used to implement the LocationStrategy.
Am I not supposed to inject CustomPathLocationStrategy in my own components or other services? Or am I doing it wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当您添加提供商时。
提供
属性定义indectionToken
或键以识别该提供商。useclass
,usefactory
...仅告诉喷油器,如果有人要求它如何创建该依赖关系。因此,当您添加这样的提供商时:
您基本上是在告诉应用程序,如果某些元素要求
locationstrategy
,它应该使用code> custompathlocationstatrategaty
class来创建依赖关系和依赖关系将其还给它,或者如果已经创建了它,请将现有实例归还。因此,在组件中,您需要“询问”
locationstrategy
,并且DI系统将为您提供custompathlocationstrategy
您已告诉您使用的实例。干杯
When you add a provider. The
provide
property defines theInjectionToken
or key to identify that provider. TheuseClass
,useFactory
,... only tells the injector how to create that dependency if someone ask for it.So when you add a provider like this:
You are basically telling the app, that if some element asks for a
LocationStrategy
, it should use theCustomPathLocationStrategy
class to create the dependency and give it back, or if it was already created give that existing instance back.So in your component, you need to 'ask' for a
LocationStrategy
, and the DI system will give you back the instance of theCustomPathLocationStrategy
you've told it to use.Cheers