如何像 Angular1 服务一样创建单例对象?
How to create singleton Object like a Angular1 Service?
我想知道如何在 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 post 无效 - 它会引发错误:
原始异常:类型错误:无法读取未定义的 属性 'post'
原始堆栈跟踪:
将服务添加到
中的提供商列表
bootstrap(AppComponent, [OtherProviders, MySingletonService]);
(不要在 providers
的任何其他地方添加 MySingletonService
。
Angular2 DI 确保相同的实例被注入所有地方。
单例模式可以通过sharedService
来实现。您必须将其注入 bootstrap
函数,例如
bootstrap(AppComponent,[sharedService]); //
我已阅读您更新的问题。 Plunker 共享您想要的对象。
我想知道如何在 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 post 无效 - 它会引发错误:
原始异常:类型错误:无法读取未定义的 属性 'post' 原始堆栈跟踪:
将服务添加到
中的提供商列表bootstrap(AppComponent, [OtherProviders, MySingletonService]);
(不要在 providers
的任何其他地方添加 MySingletonService
。
Angular2 DI 确保相同的实例被注入所有地方。
单例模式可以通过sharedService
来实现。您必须将其注入 bootstrap
函数,例如
bootstrap(AppComponent,[sharedService]); //
我已阅读您更新的问题。 Plunker 共享您想要的对象。