简体   繁体   中英

Dependancy Injection in Angular 2 - Ionic2 & typescript

I'm having some issues with bootstrapping some files in my app. Building on top of the Ionic2 tabs example.

I have a Service and a User file, each decorated with @injectable. I want 1 instance across the whole app, so i am trying to bootstrap it. I have added Platform to the providers, i'm not sure if i need 1 instance for the whole app, or per component?

import {App, Platform} from 'ionic-angular';
import {bootstrap} from 'angular2/platform/browser';
import {TabsPage} from './pages/tabs/tabs';
import {User} from './User.ts';
import {Service} from './Service.ts';
import {Type} from 'angular2/core';

@App({
    template: '<ion-nav [root]="rootPage"></ion-nav>',
    providers: [Platform]
})
export class MyApp {

    rootPage: Type = TabsPage;

    constructor(platform: Platform, user: User) {

        platform.ready().then(() => {
            user.start();
        });

    }
}

bootstrap(MyApp, [
    Service,
    User 
]);

I get 2 errors in the console

Cannot resolve all parameters for 'Platform'(?). Make sure that all the parameters are decorated with Inject or have valid type annotations and that 'Platform' is decorated with Injectable.

and then

Uncaught TypeError: Cannot read property 'getOptional' of undefined

My service for example, looks like this

import {Injectable} from 'angular2/core';

@Injectable()
export class Service {
   //
}

How to pass parameters for dependency while Injecting services in services in Angular 2 ( Ionic 2 / Angular 2 / Typescript )

This post suggests that @App is an ionic decorator that bootstraps the app. I added User and Service to the providers and all seems to be functioning. Platform need not be added to the providers.

@App({
    template: '<ion-nav [root]="rootPage"></ion-nav>',
    providers: [User, Service]
})

You don't need to specify Platform into providers of your component:

@App({
  template: '<ion-nav [root]="rootPage"></ion-nav>'
  providers: [Platform] // <------
})
export class MyApp {

  rootPage: Type = TabsPage;

  constructor(platform: Platform, user: User) {
    (...)
  }
}

Moreover I don't think that you need the .ts extension into your imports:

//import {User} from './User.ts';
//import {Service} from './Service.ts';
import {User} from './User';
import {Service} from './Service';

Do you TypeScript or ES6 into your project?

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