Angular2 global service provider

后端 未结 5 1546
轮回少年
轮回少年 2020-12-14 20:49
/app
        - app.component.ts 
        - app.component.html (hide/show: menu bar)
        - app.global.service.ts (Public varible LoginSuccess:boolean)
        - m         


        
5条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-14 21:19

    You should provide GlobalService at bootstrap, and not for each component:

    bootstrap(AppComponent, [GlobalService])
    
    @Component({
      providers: [], // yes
      // providers: [GlobalService], // NO.
    })
    class AppComponent {
      constructor(private gs: GlobalService) {
        // gs is instance of GlobalService created at bootstrap
      }
    }
    

    This way GlobalService will be a singleton.

    For more advanced approach see this answer.

提交回复
热议问题