如何在 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屋!