简体   繁体   English

Angular 2单件服务不作为单身人士

[英]Angular 2 singleton service not acting as singleton

So i've got a service called TargetService that im injecting into various other components. 所以我有一个名为TargetService的服务,它注入了各种其他组件。 This TargetService has a property called Targets which is a collection of Target objects. 此TargetService有一个名为Targets的属性,它是Target对象的集合。

My problem is that I want this collection to persist after routing to another view. 我的问题是我希望这个集合在路由到另一个视图后仍然存在。 My routes are working fine, but as soon as the route changes, the Service loses the content of any variables, essentially, its re-initializing the Service. 我的路由工作正常,但是一旦路由发生变化,服务就会丢失任何变量的内容,本质上,它会重新初始化服务。 My understanding was that these injected services are to be singletons that can be passed around? 我的理解是这些注入的服务是可以传递的单身人士?

In the following example, on the TargetIndex I click a button that populates the Targets[] object on the service ( this.targetService.targets = ts; ). 在以下示例中,在TargetIndex上,单击一个按钮,该按钮填充服务上的Targets[]对象( this.targetService.targets = ts; )。 Works fine, then I route to the TargetShow page, and then back to this index and now this Targets[] property is empty, when I want it to contain what i've already populated. 工作正常,然后我路由到TargetShow页面,然后回到这个索引,现在这个Targets[]属性是空的,当我希望它包含我已经填充的。

What am I missing here? 我在这里错过了什么?

App.Module App.Module

const routes: Routes = [
  { path: '', redirectTo: 'targets', pathMatch: 'full'},
  { path: 'targets', component: TargetIndexComponent },
  { path: 'targets/:id', component: TargetShowComponent }
]

@NgModule({
  declarations: [
    AppComponent,
    TargetComponent,
    TargetIndexComponent,
    TargetShowComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    ReactiveFormsModule,
    HttpModule,
    RouterModule.forRoot(routes)
  ],
  providers: [TargetService],
  bootstrap: [AppComponent]
})
export class AppModule { }

TargetService TargetService

@Injectable()
export class TargetService {
  public targets: Target[];

  constructor(private http: Http) {}

  getTargets(hostname: String): Observable<Target[]> {
    return this.http.request(`url`).map(this.extractData);
  }

  private extractData(res: Response) {
    let body = res.json();
    return body || [];
  }

}

TargetIndex TargetIndex

@Component({
  selector: 'app-targets',
  templateUrl: './target-index.component.html',
  styleUrls: ['./target-index.component.css'],
  providers: [TargetService]
})
export class TargetIndexComponent implements OnInit {
  loading = false;

  constructor(private http: Http, private targetService: TargetService) {}

  loadTargets(hostname: HTMLInputElement) {
    this.loading = true;
    this.targetService.getTargets(hostname.value)
    .subscribe((ts: Target[]) => {
      this.targetService.targets = ts;
      this.loading = false;
    })
  }

  ngOnInit() {
  }

}

TargetShow TargetShow

@Component({
  selector: 'app-target-show',
  templateUrl: './target-show.component.html',
  styleUrls: ['./target-show.component.css'],
  providers: [TargetService]
})
export class TargetShowComponent implements OnInit {
  id: string

  constructor(private route: ActivatedRoute, private targetService: TargetService) {
    route.params.subscribe(params => { this.id = params['id']; })
  }

  ngOnInit() {
  }

}

Try to remove TargetService from components providers, cause you already added it in module providers. 尝试从组件提供程序中删除TargetService,因为您已将其添加到模块提供程序中。 When you add this service to components providers, DI creates new instances of it. 将此服务添加到组件提供程序时,DI会创建它的新实例。

Here is quote from https://angular.io/docs/ts/latest/guide/dependency-injection.html : 以下是https://angular.io/docs/ts/latest/guide/dependency-injection.html的引用:

When to use the NgModule and when an application component? 何时使用NgModule和应用程序组件? On the one hand, a provider in an NgModule is registered in the root injector. 一方面,NgModule中的提供程序在根注入器中注册。 That means that every provider registered within an NgModule will be accessible in the entire application. 这意味着在整个应用程序中可以访问在NgModule中注册的每个提供者。

On the other hand, a provider registered in an application component is available only on that component and all its children. 另一方面,在应用程序组件中注册的提供程序仅在该组件及其所有子组件上可用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM