在 Angular2 中编写可注入服务

Writing an injectable service in Angular2

我的 Angular 服务中的数据不断重置。 它不会在两个组件之间保留缓存。

有大神知道怎么解决吗

import {Injectable} from '@angular/core';

@Injectable()
export class PillarService {
  public data: string = null;
}

Plnkr http://plnkr.co/edit/9okaVfVSsRhPxexP9HNw

似乎你想要一个单例对象,所以为此在 bootstrap 函数中注入服务,以确保它的实例只创建一次。

bootstrap(App, [appRouterProviders, PillarService])
  .catch(err => console.error(err));

然后将其从 providers 数组中删除以停止再次实例化。