0

I have an issue with observables in Angular 2. I can retrieve data from a DB using a service and can console.log the data in my service and resolver files, but I am unable to pass the data into my component.

I am using a service to query a database:

getExamQuestion(query) {
  return this.http.get('api/question/1/1').pipe(tap(data => {
    console.log("questiondata", data)  // This logs the expected data
  }));
}

constructor(
      private examdataservice:ExamdataService){
    }
    resolve(route: ActivatedRouteSnapshot) {

      return this.examdataservice.getExamQuestion(route.params).pipe(tap(data => {
    console.log("questiondata", data)  // This logs also the expected data
  }));
     
    }

My component has the following code, but I am unable to retrieve the data from the service/resolver:

ngOnInit(): void {
    this.qData = this.route.snapshot.data['ExamResolver']
    console.log("data", this.qData) // This logs 'undefined'
  }

How can I get my component to access the resolved data? Any advice would be greatly appreciated.

  • Thanks for your quick reply, I had the following path defined in my app routing module: { path:'examquestions/:id/:qid', component:ExamquestionsComponent, resolve:{exam:ExamResolver} } I had been referencing the actual resolver. I have made the change but it now returns null instead of undefined, despite the data being present in the console.log statements in the service and resolver. Any ideas? – gangstaShanks May 08 '20 at 15:16

1 Answers1

1

You have to configure your route to make your resolved data accessible in your component. For example, you should have a route to your component like this :

{
  path: 'path/to/your/component',
  component: YourComponent,
  resolve: {
    examQuestions: YourResolver
  }
}

And then you can access data in your component :

  ngOnInit(): void {
    this.qData = this.route.snapshot.data['examQuestions'];
    console.log("data", this.qData); // This logs 'undefined'
  }
thib_o_o
  • 156
  • 5