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

Che*_*yne 10 dependency-injection angular

所以我有一项服务称为TargetServiceim注入其他各种组件.此TargetService具有一个称为对象Targets集合的属性Target.

我的问题是我希望这个集合在路由到另一个视图后仍然存在.我的路由工作正常,但是一旦路由发生变化,服务就会丢失任何变量的内容,本质上,它会重新初始化服务.我的理解是这些注入的服务是可以传递的单身人士?

在以下示例中,在TargetIndex上,单击一个用于填充Targets[]服务(this.targetService.targets = ts;)上的对象的按钮.工作正常,然后我路由到TargetShow页面,然后回到这个索引,现在这个Targets[]属性是空的,当我希望它包含我已经填充的.

我在这里错过了什么?

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 { }
Run Code Online (Sandbox Code Playgroud)

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 || [];
  }

}
Run Code Online (Sandbox Code Playgroud)

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() {
  }

}
Run Code Online (Sandbox Code Playgroud)

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() {
  }

}
Run Code Online (Sandbox Code Playgroud)

Nik*_*lai 12

尝试从组件提供程序中删除TargetService,因为您已将其添加到模块提供程序中.将此服务添加到组件提供程序时,DI会创建它的新实例.

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

何时使用NgModule和应用程序组件?一方面,NgModule中的提供程序在根注入器中注册.这意味着在整个应用程序中可以访问在NgModule中注册的每个提供者.

另一方面,在应用程序组件中注册的提供程序仅在该组件及其所有子组件上可用.