angular - 从子 @Input setter 访问提供者方法 - Ionic2/Angular2

标签 angular typescript ionic2

我正在尝试从我的组件 @Input 方法访问提供程序类。但是,当调用 @Input 方法时,提供程序似乎不可用

以下是我的代码

#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”

所以我相信调用 @Input 方法时 provider: MyProvider; 不会加载。但如果我在构造函数中使用它,效果很好。 如何访问 @Input 方法内的提供程序方法?

最佳答案

这可能听起来令人困惑,但您收到的错误是因为提供程序没有作为参数包含在构造函数中(因此,您的构造函数没有创建 MyProvider类)。

请查看this plunker 。就像您可以看到的那样,即使我们在 @Input setter 拦截器中使用 myProvider 实例,构造函数也已经创建了服务的实例,因此您可以调用 sampleMethod() 没有问题。

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) {

  }
}

因此,如果您只需在构造函数中添加 private myProvider: MyProvider 参数,您的代码应该可以正常工作:)

关于angular - 从子 @Input setter 访问提供者方法 - Ionic2/Angular2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38986839/

相关文章:

Angular 2 : Get reference to component property from attribute directive

typescript - webpack 找不到 src,但应该不是在找

html - 在 Angular 2 的表格中显示弹出窗口

Angular 服务测试 : Cannot find name 'asyncData'

java - 我已允许 @CrossOrigin(origins ="*") 注释,但它仍然不起作用。谁能告诉我这里出了什么问题吗?

angular - 如何将条件错误检查从 NgIf 移至 typescript 文件?

typescript - 使用 typings 在 Ionic/TypeScript 中导入 JS 库时出现编译错误

typescript - ionic 滑动手势不适用于手机

javascript - 我如何实现 Angular2 时钟

javascript - Angular 下拉菜单从硬编码数据切换到来自服务的实时数据