So, I have a service called TargetService
, which implants in various other components. This TargetService has a Targets
property, which is a collection of Target
objects.
My problem is that I want this collection to persist after routing to a different view. My routes work fine, but as soon as the route changes, the Service loses the contents of any variables, in fact, its reinitialization of the Service. As far as I understand, should these injectable services be monophonic that can be transferred?
In the following example, on TargetIndex, I press a button that populates the Targets[]
object in the service ( this.targetService.targets = ts;
). It works well, then I go to the TargetShow page and then return to this index, and now this Targets[]
property is empty when I want it to contain what I have already filled.
What am I missing here?
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 { }
Targetgetervice
@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() { } }