所以我有一个服务叫TargetService
即时通讯注入到各种其他组件。此TargetService有一个名为Targets
的属性,它是Target
对象的集合。角度2单身服务不作为单身人士
我的问题是,我希望此集合在路由到另一个视图后保留。我的路由工作正常,但只要路由发生变化,服务就会丢失任何变量的内容,本质上,它会重新初始化服务。我的理解是,这些注入的服务是可以传递的单身人士吗?
在以下示例中,在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 { }
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() {
}
}
谢谢先生!当我这样做时,Atom会抱怨我失踪的财产,但它编译得很好,并按预期工作。我认为Atom TypeScript只是有点bug而已。 – Cheyne