Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access component from service

Tags:

angular

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();
    }
}
like image 510
ncohen Avatar asked Oct 09 '16 12:10

ncohen


Video Answer


2 Answers

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!
        }


    }
like image 142
Mohsen Avatar answered Oct 16 '22 16:10

Mohsen


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.

like image 1
Prezes Avatar answered Oct 16 '22 15:10

Prezes