How to get new instance/reload all services on logout in Angular2

好久不见. 提交于 2019-12-12 18:26:53

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!