theburouc theburouc - 1 year ago 155
AngularJS Question

Inject a provider to root injector in angular 1 angular 2 hybrid app

I am developing a hybrid ng1 ng2 app. The app is based on ng1, then, using the upgrade adapter, I downgrade the ng2 components.

I would like to have a single instance of one of the ng2 providers (a service for fetching and storing data) shared between all the ng2 components, but the components don't share a common ng2 parent component so each of the components has a new instance of the provider.

Is there a way that this components could share a single instance of provider, without using a parent ng2 component?

Answer Source

Edit: answer is outdated, since rc5 release you should use NgModule for this.

Just use addProvider method of UpgradeAdapter.

Like so:

import { UpgradeAdapter } from '@angular/upgrade';
import { YourService} from "./YourService";

const upgradeAdapter = new UpgradeAdapter();

After this YourService is added to root injector and you don't need to specify it in your other components or services:

    selector: 'cmp-selector',
    template: '...',
    // Don't specify YourService again or you will receive another instance
    // providers: [YourService] 
export class SomeComponent {
    constructor(private service: YourService) {}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download