简体   繁体   English

从服务访问组件

[英]Access component from service

In angular 2, is it possible to access the calling component (component that is calling the service) from the service?在 angular 2 中,是否可以从服务访问调用组件(正在调用服务的组件)?

Let's say my component is:假设我的组件是:

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

export class MyComponent{

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

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

And my service would be:我的服务是:

@Injectable()

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

        myComponent.callMe();
    }
}

this is wrong to call component from service.从服务中调用组件是错误的。 you shuold call service in component!你应该在组件中调用服务! this is architecture of angular 2. read this这是 angular 2 的架构。阅读此内容

Service:服务:

 @Injectable()

    export class Service{
        accessComponent(){

    alert('Hi!')

        }
    }

Component:组件:

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

    export class MyComponent{

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


    }

To achieve that, you could create Subject in service and emit next on it in the service.要实现这一点,您可以在服务中创建主题并在服务中发出next主题。

Then subscribe to the subject in your component, calling the method once stream will emit the value.然后订阅组件中的主题,一旦流将发出值,就调用该方法。

First of all, you should not use addEventListener , because to handle click, angular2 has it's own way to do that - <div (click)="calledFunc()"></div> .首先,你不应该使用addEventListener ,因为要处理点击,angular2 有它自己的方法 - <div (click)="calledFunc()"></div> It is idiomatic way to add click event in angular2.这是在 angular2 中添加点击事件的惯用方式。 (According to comment discussion) (根据评论讨论)

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

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