Angular 2无法访问类函数

时间:2017-02-03 11:25:20

标签: angular typescript

我有一个已知的类,其中有一个名为checkRev的函数,但当我尝试在onNgInit上使用它时,它说" this.known.checkRev不是函数"

我的课程:

coverage

我的组件

export class Known {
   constructor(args...){}
   public checkRev(){
    code...
   }
}

@edit 我通过输入

传递已知对象
export class KnownItem implements OnInit {
@Input('userInfo') known: Known;
ngOnInit(){
   this.known.checkRev();
}

知识阵列

<sh-known-item *ngFor="let known of knowns" [userInfo]="known"></sh-known-item>

推入阵列

private knowns: Array<Known> = [];

@EDIT 2 我在checkRev()里面的代码太长了,不能把它放在这里

2 个答案:

答案 0 :(得分:0)

您实际上不需要将其作为输入传递,您可以在构造函数方法中实现它,如

export class KnownItem implements OnInit {
  constructor (private known: Known){}
  ngOnInit (){
    this.known.checkRev()
  }
}

答案 1 :(得分:0)

你需要拥有// returns an array of all the router-outlets component currently rendered private getComponentsChain(routerOutletMap: RouterOutletMap) { const outlets: any = (<any>routerOutletMap)._outlets, outletsList = [], components = []; _.forOwn(outlets, (value: RouterOutlet, key: string) => { outletsList.push(value); components.push(value.component); }); const recursiveComponents = _.flatMap( outletsList, (o: RouterOutlet) => this.getComponentsChain(o.outletMap)); return [...components, ...recursiveComponents]; } /* ...then somewhere in component: */ console.log(this.getComponentsChain((<any>this.router).outletMap)); 的一些属性,无论你有什么属性,你都必须能够在该对象上执行某些功能。

所以,例如你的班级应该是这样的:

 .form {
    float: right;
  background: rgba(19, 35, 47, 0.9);
  padding: 40px;
  max-width: 600px;
  margin: 40px auto;
  border-radius: 4px;
  box-shadow: 0 4px 10px 4px rgba(19, 35, 47, 0.3);
    margin-right: 20px; /*what ever you want*/
}

然后你的代码应该正常工作。经过测试,它运行良好!这里有一个 工作 plunker