因此,我有一项名为TargetService
的服务,可将其注入(inject)其他各种组件中。此TargetService具有一个称为Targets
的属性,该属性是Target
对象的集合。
我的问题是,我希望此集合在路由到另一个 View 后仍然存在。我的路由运行良好,但是一旦路由更改,该服务就会丢失任何变量的内容,本质上是它会重新初始化该服务。我的理解是这些注入(inject)的服务要成为可以传递的单例吗?
在以下示例中,在TargetIndex上,单击一个按钮,该按钮将填充服务上的Targets[]
对象(this.targetService.targets = ts;
)。工作正常,然后我路由到TargetShow页面,然后返回到该索引,现在当我希望它包含已经填充的内容时,此Targets[]
属性为空。
我在这里想念什么?
应用程序模块
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
@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
@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
@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() {
}
}
最佳答案
尝试从组件提供程序中删除TargetService,因为您已将其添加到模块提供程序中。当您将此服务添加到组件提供程序时,DI会创建该服务的新实例。
这是https://angular.io/docs/ts/latest/guide/dependency-injection.html的报价:
关于Angular 2单例服务不充当单例,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40662564/