我有一个名为TargetService的服务,我正在将它注入到其他各种组件中。这个TargetService有一个名为Targets的属性,它是Target对象的集合。
我的问题是,我希望这个集合在路由到另一个视图后保持不变。我的路由运行良好,但是一旦路由发生变化,服务就会丢失任何变量的内容,实际上,它正在重新初始化服务。我的理解是,这些注入的服务是可以传递的单身人士吗?
在下面的示例中,在TargetIndex上,我单击一个在服务(this.targetService.targets = ts;)上填充Targets[]对象的按钮。这很好,然后我路由到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 { }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',
providers: [TargetService]
})
export class TargetIndexComponent {
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;
})
}
}TargetShow
@Component({
selector: 'app-target-show',
templateUrl: './target-show.component.html'
providers: [TargetService]
})
export class TargetShowComponent {
id: string
constructor(private route: ActivatedRoute, private targetService: TargetService) {
route.params.subscribe(params => { this.id = params['id']; })
}
}发布于 2016-11-17 20:07:18
尝试从组件提供程序中删除TargetService,因为您已经在模块提供程序中添加了它。当您将此服务添加到组件提供程序时,DI将创建它的新实例。
以下是https://angular.io/docs/ts/latest/guide/dependency-injection.html的引文:
何时使用NgModule,以及当应用程序组件?一方面在根注入器中注册了NgModule中的提供者时。这意味着在NgModule中注册的每个提供者都可以在整个应用程序中访问。 另一方面,在应用程序组件中注册的提供程序只能在该组件及其所有子组件上可用。
https://stackoverflow.com/questions/40662564
复制相似问题