在Component的Input上调用函数

时间:2016-10-01 11:38:15

标签: angular

所以我有一个看起来像这样的组件:

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 个答案:

答案 0 :(得分:2)

为组件创建公共服务并在服务中添加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();
    }

 }
相关问题