简体   繁体   中英

Access component from service

In angular 2, is it possible to access the calling component (component that is calling the service) from the service?

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

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.

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> . It is idiomatic way to add click event in angular2. (According to comment discussion)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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