问题
I am developing angular2 application which is similar to Plunkr link provided at the end.
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));
}
}
Plunkr Link
回答1:
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.
来源:https://stackoverflow.com/questions/41038709/how-to-get-new-instance-reload-all-services-on-logout-in-angular2