2017-10-13 25 views
1

我们有一些奇怪的依赖注入问题,我们不明白...我尝试说明情况。服务功能用作输入参数时,不会注入Angular Service的依赖关系输入参数

我们有一个addressComponent,我们注入了我们的addressService。因此,这是服务(见两次注射http和AppConfig的):

@Injectable() 
export class AdresseService{ 

    constructor(private http: Http, private appConfig: AppConfig) { 
     .... 
    } 

    makeSth() { 
     this.http.get(.....); 
    } 
} 

这是组件:

export class AdresseComponent { 

    constructor(public adresseService: AdresseService) { 
    } 
} 

该组件这个片段在其HTML:

<other-component-tag [fn]="adresseService.makeSth"</other-component-tag> 

因此,我们在组件中注入服务,并将此服务的功能作为参数提供给另一个组件。而这是其他组件,我们实际上调用这个函数:

export class OtherComponent { 

    @Input() fn; 

    callFunction() { 
    this.fn(); 
    } 
} 

所以问题:功能“makeSth”的AdresseService实际上是调用,但该服务依赖(比如HTTP或AppConfig的)不注射。因此,我们在AdresseService的makeSth方法中出现一些错误,如“get of undefined ....”。这里发生了什么?

当我们将服务定义为其他组件的依赖关系时,它起作用。当我们给整个服务(而不是只给它一个函数)作为参数时,它也可以工作。但为什么这个设置不起作用?

+0

可以更新代码module.ts? – Chandru

回答

3

您正在传递一个类函数作为回调函数。 在这种情况下,this的值发生变化,新的this将不会有http和其他注入属性。

使用箭头函数或绑定函数作为回调函数。

在您的组件,

export class AdresseComponent { 

    makeSth:any; 

    constructor(public adresseService: AdresseService) { 
    this.makeSth =() => this.adresseService.makeSth() 
    } 
} 

而在你的HTML,

<other-component-tag [fn]="makeSth"</other-component-tag> 
+0

非常感谢你! – akcasoy