Andres Felipe
Andres Felipe

Reputation: 4330

Angular 2 and Resolve route

I am learning Angular and I am pretty new on it. I want to display some data in a view, and the data comes from the server, I know that it is async so I have been trying to use resolves to get data before view render, but I cannot get it in the component, this is what I've done.

MateriasResolve.ts

import { Injectable } from '@angular/core';
import { Resolve, ActivatedRouteSnapshot } from '@angular/router';
import { UserService } from '../../services/user.service';
import 'rxjs/add/operator/first'
import { Observable } from 'rxjs/Observable';
import { Materias } from './materias.model';

@Injectable()
export class MateriasResolve implements Resolve<any> {

      public user_id = localStorage.getItem('userid');
      public colegio = localStorage.getItem('colegio');

      constructor(private userService: UserService) { }

      resolve(route: ActivatedRouteSnapshot): Observable<any> | Promise<any> | any {
      return this.userService.getTeacherMaters(this.user_id, this.colegio).map(data => {
  console.log(data); >>here i get the data in the console, no problem here
}).first();
}

}

the service:

getTeacherMaters(id, colegio_code) {
    this.auth.createAuthenticationHeaders();
    return this.http.get(globals.API_DOMAIN + "/materias/" + id + "/" + colegio_code, this.auth.options)
        .map(res => res.json());
}

and my part of my component:

getMaterias() {
this.materias = this.userService.getTeacherMaters(this.user_id, this.colegio)
  .subscribe(data => {
    console.log("data ------------- " + data);
    return data.materias;
  });
console.log(this.materias);
}

I need to put the data in the materias var, but all I get in the console.log is:

Subscriber {closed: false, _parent: null, _parents: null, _subscriptions: Array(1), syncErrorValue: null…}

Upvotes: 0

Views: 197

Answers (1)

Teddy Sterne
Teddy Sterne

Reputation: 14221

There are a couple of things wrong here.

First, you are mapping the data that comes from getTeacherMaters but you are not returning any data so it is most likely falling through here. You need to update it to this:

return this.userService.getTeacherMaters(this.user_id, this.colegio).map(data => {
  console.log(data); >>here i get the data in the console, no problem here
  return data;
}).first();

Second, you are saving a copy of the subscription but I suspect that you want to save the data to this.materias. Because the data request is async you will not get the data until inside of the subscribe block and calling subscribe will return a subscription that you can cancel. Update your getMaterias method to be:

getMaterias() {
    this.userService.getTeacherMaters(this.user_id, this.colegio)
        .subscribe(data => {
            this.materias = data;
            console.log(this.materias);
         });
}

Upvotes: 1

Related Questions