2016-10-01 51 views
0

所以我有一个组件,它看起来是这样的:呼叫功能的组件的输入

export class TAComponent implements OnInit { 
    @Input() postInfo : TracklistPost; 
    youtubeUrlOriginal : string; 

    ngOnInit() : void { 
     this.youtubeUrlOriginal = this.postInfo.getYoutubeUrl(); 
    } 
} 

和类:

export class TracklistPost { 
    play_urls  : PlayUrl[]; 

    public getYoutubeUrl() : string { 
     return this.play_urls[1].value; 
    } 
} 

当我打电话从TAComponent的getYoutubeUrl()函数,我得到这个函数没有定义的错误。在Angular2中如何做到这一点?

回答

1

两个组件创建一个共同的服务,在服务中添加getYoutubeUrl(),并使用该服务在这两个组件

import { Injectable } from '@angular/core'; 
export class CommService { 


    play_urls  : PlayUrl[]; 
    constructor() { 
    } 

    public getYoutubeUrl() : string { 
     return this.play_urls[1].value; 
    } 
} 

现在,在这两个部件的母公司注入该服务并使用此服务如下图所示

export class TAComponent implements OnInit { 
    @Input() postInfo : TracklistPost; 
    youtubeUrlOriginal : string; 

    constructor(public commService : CommService) { } 

    ngOnInit() : void { 
     this.youtubeUrlOriginal = this.commService.getYoutubeUrl(); 
    } 

} 
+0

好的谢谢,编辑为我想它看起来像但它现在工作。我想我太习惯于编写Java ... 只是一个小问题,我应该在“导出类CommService”之前添加@Injectable(),还是不需要? – CounterFlame