如何像Angular1服务一样创建单例对象?

时间:2016-03-10 12:35:11

标签: angular angular2-di

我想知道如何在Angular2中创建单例对象,它将在应用程序的整个生命周期中保存一些属性的值 - 这样我就可以在许多组件中使用它并注入它。

有什么想法吗?

由于

我的尝试是:

bootstrap(MyApp,[ROUTER_PROVIDERS,
HTTP_PROVIDERS,
provide(LocationStrategy, {useClass: HashLocationStrategy}),
provide(APP_BASE_HREF, {useValue: '/'}),Login])

where 

Login:

@Injectable()
export class Login {
    public  username: string = "any";
    constructor(private _http:Http, private _router:Router){

    }

    public static login(username,password){
        var creds = 'username=' + username+'&password='+password;
        this._http.post('/authentication/login',creds,{headers: contentHeaders})
            .subscribe(
                success =>{
                    this.username = success.json().username;
                    this._router.navigate(['Dashboard']);
            },
                error =>{
                    console.log('Wrong creds')
            });
    }

    public getUsername(){
        return this.username;
    }
}

在这种情况下,getUsername()有效,但是this._http帖子没有 - 它会抛出错误:

ORIGINAL EXCEPTION:TypeError:无法读取未定义的属性“post” 原始STACKTRACE:

2 个答案:

答案 0 :(得分:3)

单身模式可以通过sharedService实现。您必须将其注入bootstrap函数,如

bootstrap(AppComponent,[sharedService]); // 

我已阅读您更新的问题。 Plunker 分享您想要的对象。

答案 1 :(得分:1)

将服务添加到

中的提供者列表中
bootstrap(AppComponent, [OtherProviders, MySingletonService]);

(不要将MySingletonService添加到providers的任何其他地方。

Angular2 DI确保在任何地方注入相同的实例。

相关问题