如何在Angular2注销时获取新实例/重新加载所有服务 [英] How to get new instance/reload all services on logout in Angular2
问题描述
我正在开发angular2应用程序,该应用程序类似于最后提供的Plunkr链接.
I am developing angular2 application which is similar to Plunkr link provided at the end.
在HeroService中,我有一个属性clickCount,在点击英雄时会增加.但是登录后,我想重置此参数.我不想使用该服务并重置其值(实际上,在我的应用程序中,我正在使用许多服务,因此无法使用每个服务并在注销时重置其值).
In HeroService i have an property clickCount, which will be incremented on click of hero. But After login i want to reset this parameter. I don't want to use the service and reset its value (actually in my application i am using many services, so cannot use each service and reset its value on logout).
是否有任何方法可以在不重新加载整个应用程序的情况下针对特定操作重置/重新加载服务. 英雄服务如下
Is there any method to reset/reload service on particular action without reloading entire application. Hero service is as below
import { Hero } from './hero';
import { HEROES } from './mock-heroes';
import { Injectable } from '@angular/core';
@Injectable()
export class HeroService {
getHeroes(): Promise<Hero[]> {
return Promise.resolve(HEROES);
}
getHeroesSlowly(): Promise<Hero[]> {
return new Promise<Hero[]>(resolve =>
setTimeout(resolve, 2000)) // delay 2 seconds
.then(() => this.getHeroes());
}
getHero(id: number): Promise<Hero> {
return this.getHeroes()
.then(heroes => heroes.find(hero => hero.id === id));
}
}
推荐答案
除了销毁并重新引导整个Angular2应用程序外,我认为没有其他方法.
I don't think there is a way except destroying and re-bootstrapping the whole Angular2 application.
我将使用可共享的所有其他服务使用的全局共享服务. 共享服务发出一个事件,通知其他人应重置它们,然后这些服务自己完成.
I would just use a globally shared service with an observable all other services subscribe to. The shared service emits an event to notify the others they should reset and these services then do it by themselves.
这篇关于如何在Angular2注销时获取新实例/重新加载所有服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!