Here is my service:
import { Injectable } from '@angular/core';
import { Headers, Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import {Router} from '@angular/router';
// Import RxJs required methods
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
@Injectable()
export class CaseService {
public caseData: any;
constructor(private _http: Http, private r:Router) {}
public GetCase() {
const url = 'http://localhost:55130/api/case?caseId=' + 123;
return this._http.get(url)
.map((res: Response) => res.json());
}
}
My app.component.ts is the one that is bootstrapped, so on init, I make a call to my service and populate caseData:
import { Component, OnInit } from '@angular/core';
import { CaseService } from 'app/case.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
constructor(private _caseService: CaseService) { }
ngOnInit(): void {
this._caseService.GetCase().subscribe(data => {
this._caseService.caseData = data;
console.log(this._caseService.caseData);
});
}
}
When I console.log(this._caseService.caseData), I can see the object.
Now in my other component home, when I try to access this, it tells me undefined. When I just console this._caseService, I can see the caseData object at the home component level:
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { CaseService } from 'app/case.service';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
case;
constructor(private _caseService: CaseService) { }
ngOnInit() {
console.log(this._caseService.caseData); //undefined
console.log(this._caseService); //I can see the caseData object in browser console
}
}
Am I sharing the data incorrectly? I did notice when I console out, it looks like it is consoling out home component first and then app component. If app component is bootstrapped, shouldn't that be the first one?