问题描述
我正在尝试从我的组件 @Input
方法访问提供程序类。但是,当调用 @Input
方法时似乎提供者不可用
I'm trying to access a provider class from my components @Input
method. However it seems like the provider is not available when the @Input
method is called
以下是我的代码
#provider
import { Injectable } from '@angular/core';
import 'rxjs/add/operator/map';
@Injectable()
export class MyProvider {
constructor() {}
sampleMethod(){
return 'sample method';
}
}
#component
import { Component, Input } from '@angular/core';
import {MyProvider} from '../../providers/my-provider/my-provider';
import { NavController} from 'ionic-angular';
@Component({
selector: 'selected-options',
templateUrl: 'build/components/selected-options/selected-options.html',
inputs: ['node']
})
export class SelectedOptions {
provider: MyProvider;
@Input()
set node(n: any){
this.provider.sampleMethod();
}
}
#page (where I call the component)
<selected-options [node]="node.Name"></selected-options>
所以问题在于行
this.provider.sampleMethod();
我得到的错误是原始异常:TypeError:无法读取未定义的属性'sampleMethod'
。
所以我相信提供者:MyProvider;
在 @Input 方法。但是如果我在构造函数中使用它,这可以正常工作。
如何在 @Input
方法中访问提供者方法?
So I believe provider: MyProvider;
is not loaded when the @Input
method is called. But this works fine if I use it inside the constructor.How can I access a provider method inside a @Input
method?
推荐答案
这可能听起来很混乱,但是你得到的错误是因为提供程序没有作为参数包含在构造函数中(因此,你的构造函数没有创建<$ c $的实例) c> MyProvider class)。
It may sound confusing, but the error you're getting is because the provider is not being included in the constructor as a parameter (and because of that, your constructor is not creating an instance of the MyProvider
class).
请看一下。就像你可以在那里,即使我们在 @Input
setter拦截器中使用 myProvider
实例,构造函数已经创建服务的实例,所以你可以毫无问题地调用 sampleMethod()
。
Please take a look at this plunker. Like you can se there, even though we use the myProvider
instance in the @Input
setter interceptor, the constructor already created the instance of the service, so you can call the sampleMethod()
without problems.
import { Component, Input } from "@angular/core";
import { MyProvider } from './my-provider.ts';
@Component({
templateUrl:"child.html",
selector: 'child-selector',
inputs: ['node']
})
export class ChildPage {
private result: string;
@Input()
set node(node: string){
// Because the provider instance is injected on the constructor, we can
// call the sampleMethod() here
node = node + ' from ChildPage';
this.result = this.myProvider.sampleMethod(node);
}
// Injects an instance of the MyProvider class
constructor(private myProvider: MyProvider) {
}
}
因此,如果您只需添加私有myProvider:MyProvider
您的构造函数中的参数应该可以正常工作:)
So if you just add the private myProvider: MyProvider
parameter in your constructor your code should work fine :)
这篇关于从子@Input setter访问提供者方法 - Ionic2 / Angular2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!