繁体   English   中英

从服务访问组件

[英]Access component from service

在 angular 2 中,是否可以从服务访问调用组件(正在调用服务的组件)?

假设我的组件是:

@Component({
    selector: 'my-component',
    templateUrl: 'myTemplate.html',
    providers: [Service]
})

export class MyComponent{

    constructor(private service:Service) {
        service.accessComponent();
    }

    callMe(){
        console.log('hello');
    }
}

我的服务是:

@Injectable()

export class Service{
    accessComponent(){
        var myComponent = ???;

        myComponent.callMe();
    }
}

从服务中调用组件是错误的。 你应该在组件中调用服务! 这是 angular 2 的架构。阅读此内容

服务:

 @Injectable()

    export class Service{
        accessComponent(){

    alert('Hi!')

        }
    }

组件:

 @Component({
        selector: 'my-component',
        templateUrl: 'myTemplate.html',
        providers: [Service]
    })

    export class MyComponent{

        constructor(private service:Service) {
            service.accessComponent(); //and you see alert!
        }


    }

要实现这一点,您可以在服务中创建主题并在服务中发出next主题。

然后订阅组件中的主题,一旦流将发出值,就调用该方法。

首先,你不应该使用addEventListener ,因为要处理点击,angular2 有它自己的方法 - <div (click)="calledFunc()"></div> 这是在 angular2 中添加点击事件的惯用方式。 (根据评论讨论)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM