0
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?

xaisoft
  • 3,343
  • 8
  • 44
  • 72
  • Where is the provider for `CaseService`? – Partha Sarathi Ghosh Apr 06 '17 at 18:04
  • @ParthaSarathiGhosh - It is in the app..module.ts providers section – xaisoft Apr 06 '17 at 18:05
  • Are the both component in the app module? Are you using lazyloading? – Partha Sarathi Ghosh Apr 06 '17 at 18:05
  • @ParthaSarathiGhosh - Yes, both components are declared in the declarations section and AppComponent is in the bootstrap array – xaisoft Apr 06 '17 at 18:06
  • Put `console.log` in `CaseService` `constructor`. I think object of `CaseService` is being created multiple times. – Partha Sarathi Ghosh Apr 06 '17 at 18:07
  • 4
    The data is not yet available when `ngOnInit` in `HomeComponent` is accessed. You make an async call to the server which takes an awful lot of time. In the meantime you try to access the value, but only much later it actually arrives. – Günter Zöchbauer Apr 06 '17 at 18:08
  • Perhaps you want to use something like http://stackoverflow.com/questions/36271899/what-is-the-correct-way-to-share-the-result-of-an-angular-2-http-network-call-in/36291681#36291681 – Günter Zöchbauer Apr 06 '17 at 18:08
  • @GünterZöchbauer - Ah, that explains why when I tried it without making a call to the server, it worked. – xaisoft Apr 06 '17 at 18:08
  • @GünterZöchbauer - is the reason it is available in app component is because the data has come back by the time init has been called in that component. The one curiosity I have is why it seems the init of app component is called after home? – xaisoft Apr 06 '17 at 18:14
  • Yes, the function you pass to `subscribe(...)` is called by the observable when the response from the server arrives. If you move `console.log(...)` outside of `subscribe()` you also won't get a value printed. – Günter Zöchbauer Apr 06 '17 at 18:15
  • So, the only option is to either return a cached response or make an http request again? And this can be done for all components? – xaisoft Apr 06 '17 at 18:17
  • Is it possible to ensure the service has returned data before having the init function called on components? – xaisoft Apr 06 '17 at 18:18

0 Answers0