-2

This is my component:

export class CaseStudyDetailComponent implements OnInit {

casestudy: CaseStudy;

constructor ( private caseStudyService: CaseStudyService, private route: ActivatedRoute, public titleService: Title ) { }

ngOnInit() {

    this.route.params.subscribe((params: { Handle: string }) => {
        this.caseStudyService.getCaseStudy(params.Handle).subscribe(casestudy => this.casestudy = casestudy);
    });

    this.titleService.setTitle(this.casestudy.Handle);

}
}

This is the service it is calling:

    getCaseStudy(Handle: string): Observable<CaseStudy> {
    return this.http.get<CaseStudy>(`${environment.apiPath}/project/handle/${Handle}`);
}

I want to be able to access the value of 'casestudy' in the 'setTitle()' method. I might potentially just be misunderstanding expected behaviour or have my syntax wrong.

Let me know if more information is required.

TylerH
  • 20,799
  • 66
  • 75
  • 101
Caleb Kent
  • 33
  • 3
  • What does your `CaseStudyService` look like? Can you add more detail to your question? Please read [How To Ask?](https://stackoverflow.com/help/how-to-ask) for guidance on the correct way to ask a question. – prettyfly Jan 14 '19 at 12:20
  • I've edited my original question, thanks – Caleb Kent Jan 14 '19 at 12:24
  • 1
    Possible duplicate of [Observable Undefined](https://stackoverflow.com/questions/41945817/observable-undefined) – jonrsharpe Jan 14 '19 at 12:27
  • Have you logged out the value of `casestudy` returned from your service, to make sure it's actually got a value? – prettyfly Jan 14 '19 at 12:30
  • `this.caseStudyService.getCaseStudy(params.Handle).subscribe((casestudy: any) => { console.log('Returned, casestudy); this.casestudy = casestudy); });` – prettyfly Jan 14 '19 at 12:31
  • Yeah, I'm getting back a value from my service, that's not the issue, but thanks for the suggestion, I just double checked – Caleb Kent Jan 14 '19 at 12:38

1 Answers1

1

Because your console.log gets excecuted before your subscribe can set the response in the caseStudy.

To fix this put the console.log method in the subscribe

this.caseStudyService.getCaseStudy().subscribe(caseStudy => {
  ... code
  console.log(caseStudy);
});
  • Once you've assigned `casestudy` to `this.casestudy`, you can access it from another method. The reason your `console.log` is empty, is because it's executed before the call is complete. See my comment on your question to check if you're actually getting a value returned from your service. – prettyfly Jan 14 '19 at 12:32