1

So i have a very simple domain model Shell :

import {Injectable} from 'angular2/core';

@Injectable()
export class Shell {

    public loggedIn: boolean = false;

    Change(item : boolean) {
        this.loggedIn = item;
    }
}

I have an AppComponent which hold this property:

@Component({
    selector: 'my-app',
    providers: [TemplateRef],
    templateUrl: './angular/app/Index.html',
    directives: [ROUTER_DIRECTIVES, NgIf],
    viewProviders: [Shell]
})



export class AppComponent {

    public Shell: Shell

    constructor( @Inject(Shell) _shell: any) {
        this.Shell = _shell;
    }
}

and short piece of index view :

<div *ngIf="Shell.loggedIn">
    LOGGED IN!
</div>

and i have a registerview which wants to change loggedin status on successful registration:

@Component({
    templateUrl: './Angular/app/Html/Account/Register.html',
    directives: [ROUTER_DIRECTIVES],
    providers: [AccountService],
    viewProviders: [Shell]
})

export class RegisterView {
    registerForm: any;
    public Shell: Shell
    model = new RegisterVM();
    constructor(private _formBuilder: FormBuilder,
        private _http: Http,
        private _accountSerivce: AccountService,
        @Inject(Shell) _shell: any) {
        this.Shell = _shell
    }

    onSubmit(event: any) {
        this.Shell.Change(true)
    }

As you can see i attempted to make use of dependency injection, but every single time Shell is returned as a new object.

Do i really need to make Shell singleton? or are there any other ways? I am very new to angular2 so i might have overseen some very basic things, please correct me if i messed up anywhere.

Timsen
  • 4,066
  • 10
  • 59
  • 117

2 Answers2

3

For this you need to add your Shell service when bootstrapping your application:

bootstrap(AppComponent, [ Shell ]);

And remove it from all viewProviders attribute of your components:

@Component({
    selector: 'my-app',
    providers: [TemplateRef],
    templateUrl: './angular/app/Index.html',
    directives: [ROUTER_DIRECTIVES, NgIf],
    // viewProviders: [Shell] <-------
})

It's because of the way the "hierarchical injectors" feature of Angular2 works. For more details you could have a look at this question:

Community
  • 1
  • 1
Thierry Templier
  • 198,364
  • 44
  • 396
  • 360
0

Indeed you need to make Shell a singleton. You have to add the service in your bootstrap method as a provider.

Michael Desigaud
  • 2,115
  • 1
  • 15
  • 15