Access key data across entire app in Angular 2 & Ionic 2

前端 未结 3 1185
独厮守ぢ
独厮守ぢ 2020-12-11 06:27

What would be the best way to store data that I can access across an entire app in Angular 2 and Ionic 2 - typescript.

For user information my initial thought was to

3条回答
  •  难免孤独
    2020-12-11 07:07

    Using a provider to hold global data is working for me in Ionic 2 beta 6, and I believe it is the recommended practice in Angular 2.

    Generate a provider from the command line: ionic g provider GlobalService Notice how the generated service is decorated with @Injectable

    Inject your service in the @App class; you do this by declaring it in the providers array:

      @App({
            templateUrl: 'build/app.html',
                  providers: [GlobalService] ,
                  config: {} // http://ionicframework.com/docs/v2/api/config/Config/
                })
    

    This will create an single instance of your provider that is accesible on every page. Wherever you need to use it, do not declare in the providers array, but on the constructor of the Page:

    @Page({
            templateUrl: 'build/pages/new-page/new-page.html',
          })
          export class NewPage{
    
           constructor(public globalService: GlobalService) {
        }
    
        someFunction(){
        this.globalService.someGlobalFunction();
        }
    

提交回复
热议问题