ionic-framework icon indicating copy to clipboard operation
ionic-framework copied to clipboard

Overlay Providers are breaking custom app providers

Open danbucholtz opened this issue 10 years ago • 13 comments

Sorry about the wordsmith'd title.

This is a pretty important issue.

If I have a page that takes an injected dependency via construction injection that is custom to my app (I am providing at the root component level), the page errors out due to being unable to find the dependency when opened in a Modal. When I push the page onto the nav controller, it works as expected.

import {PROVIDERS} from './app-providers';

@Component({
  template: `<ion-nav [root]="rootPage"></ion-nav>`,
  providers: PROVIDERS
})
export class MyApp {
   // stuff in the app
}

Anything from the PROVIDERS array errors out when injected in a Modal. I am sure this applies to other overlays like Popover as well.

Thanks, Dan

danbucholtz avatar Jul 01 '16 16:07 danbucholtz

Could you improve this test and try to make a reproducible example? https://github.com/driftyco/ionic/commit/da6215c08e2c87e210cf7617dead5fc86a91824c

adamdbradley avatar Jul 02 '16 01:07 adamdbradley

I ran into the same issue with Ionic2 nightly (pre beta-11).

The issue seems to happen when creating/instantiating a component [c1] with dependencies as popover/modal IFF a required dependency is first introduces by the component [c2] invoking the popover creation (invoking PopoverController.create(c1) inside c2).

It seems like the popover is using the components [c2] parent injector instead of the components injector itself when trying to instantiate component [c1], thus failing.

On the other hand, when component [c1] is created/instantiated via a nav-controller inside component [c2], (eg invoking Nav.push(c1) inside c2) the correct injector is used and creation succeeds, this feels a bit inconsistent and suggests the popover could be using the wrong injector.

I tried creating a plunker for this, but could not get the ionic2 nightly version running there (and the editor is so unresponsive)... So I've created a simple webpack-based demo application instead, I hope this helps.

Hufschmidt avatar Aug 03 '16 09:08 Hufschmidt

@Hufschmidt, Thanks for the demo. Adam and I continued our discussion about this offline. This is something we still need to do.

Thanks for contributing and helping us out!

Dan

danbucholtz avatar Aug 03 '16 14:08 danbucholtz

any workaround? solution? have the same issue.

shalaby avatar Aug 08 '16 16:08 shalaby

I'm having a similar issue that I think might be related.

I have a popover with a callback to the parent controller the that calls a nav.push to the next page. Your redirected to the next page but then the 'Back' button no longer works. It seems like it breaking the page array on the nav controller.

aaronklaser avatar Aug 08 '16 17:08 aaronklaser

just ran into this issue today, can not use DI to get AngularFire into my modal login screen :-( I had to pass it in as a parameter to make everything work

here is a complete project using the latest ionic release, 2.0.0-beta.11, showing the error: https://github.com/aaronksaunders/afprovidertest-ionic2-error

import { AngularFire, AuthProviders, AuthMethods, FirebaseAuthState } from 'angularfire2';

@Page({
    templateUrl: 'build/pages/home/home.html',
    pipes: [MomentDate]
})
export class HomePage implements OnInit {
    textItems: Observable<any[]>;
    usersWithMessages: Observable<any[]>;
    authInfo: any
    displayName: any
    buttonTitle = "LOGIN"

    constructor(
        public af: AngularFire,
        public navCtrl: NavController,
        public modal: ModalController) {
        // dont do anything heavy here... do it in ngOnInit
    }

    displayLoginModal() {

        // I NEEDED TO HACK THE ANGULAR FIRE OBJECT INTO THE ModalController
        // BECAUSE OF A BUG IN IONIC...
        //
        let loginPage = this.modal.create(LoginPage, { af: this.af });
        loginPage.present();
    }
@Component({
    templateUrl: 'build/pages/login/login.html',
    directives: [REACTIVE_FORM_DIRECTIVES]
})
export class LoginPage {

    error: any
    af: any
    loginForm: FormGroup;

    constructor(public viewCtrl: ViewController,
        builder: FormBuilder,
        public _params: NavParams) {

        // HAD TO HACK IN THE AngularFire object... :-(
        this.af = _params.get("af");

        this.loginForm = builder.group({
            'email': [
                '', // default value
                [Validators.required, Validators.minLength(5)]
            ],
            'password': [
                '',
                [Validators.required, Validators.minLength(5)]
            ]
        })
    }

@shalaby this hack might work for you

aaronksaunders avatar Aug 08 '16 20:08 aaronksaunders

@adamdbradley You probably have been discussing this internally already, in that case ignore my train of taught... :wink:

The problem with popovers/modals is that they are now (as of beta-11 atleast) created on the app-root level (on the app._portal's NavController-like). Thus it sits next to all your components and their injectors / injected providers.

Since the modal (modal-component.ts:43) and the popover (popover-component:63) use their viewports injector, which is a child of the app._portal's viewport (with some intermediate parent-injectors like the modals/popovers own component injector), the only providers available are the global ones given during bootrap.

So one quick (and dirty) workaround is to add all providers you need in your models/popovers component in the bootstrap method.

Personally I modified the source code for modal-component.ts and popover-component.ts to use an injector passed along via the modals/popovers data parameter instead, not perfect, but the component can now at least 'stand on its own' like when used via the nav component.

      let injector = this._navParams.data.injector;
      if (injector) {
        let componentProviders = ReflectiveInjector.resolve([
          provide(ViewController, {useValue: this._viewCtrl})
        ]);

        injector = ReflectiveInjector.fromResolvedProviders(componentProviders, injector);
      }
      else 
        injector = this.viewport.parentInjector;

      let componentRef = this.viewport.createComponent(componentFactory, this.viewport.length, injector);

As for a long-term solution, I strongly feel that we should be able to use components as modals and popovers the same way they can be used as Nav pages. For this you should be able to (manually/explicitly) set the injector used during the actual component creation (modal-component.ts:43 & popover-component:63). This should propably happen by adding another (optional) parameter to ModalController.create(...) and PopoverController.create(...), since a modal/popover cannot (and probably sshould not) detect the component (and thus the 'correct' parent-injector) in which it was created all by itself...

Hufschmidt avatar Aug 09 '16 06:08 Hufschmidt

related: https://github.com/driftyco/ionic/issues/7621 possibly related: https://github.com/driftyco/ionic/issues/7563

jgw96 avatar Aug 09 '16 15:08 jgw96

Thinking about this issue and NgModules in the rc5 update may actually fix this. Note to self: test this issue when that hits master (hopefully tomorrow or the next day).

jgw96 avatar Aug 10 '16 22:08 jgw96

@jgw96 Hi Justin, is a fix still planed for the beta12, or should we look for a workaround? I cannot use ng-translate2 in my popovers, too.

Thanks!

VinceOPS avatar Sep 15 '16 14:09 VinceOPS

This is no longer applicable due to the move to NgModules in newer version of Angular 2. This will be included in Beta 12.

Thanks, Dan

danbucholtz avatar Sep 19 '16 14:09 danbucholtz

@VinceOPS,

Add providers inside ionicBootstrap and it will work in modal views.

ionicBootstrap(MyApp, [User, ChatService, ApiRequest, Elements, UserData, disableDeprecatedForms(), provideForms(),
        {
            provide: PLATFORM_PIPES,
            useValue: TranslatePipe,
            multi: true
        },
        {
            provide: TranslateLoader,
            useFactory: (http: Http) => new TranslateStaticLoader(http, 'assets/i18n', '.json'),
            deps: [Http]
        },
        TranslateService
    ], {}
);

raducostea avatar Sep 27 '16 13:09 raducostea

Thank you @raducostea

ifelere avatar Nov 09 '16 20:11 ifelere