Angular 2和Resolve路线

时间:2017-07-17 12:36:34

标签: angular

我正在学习Angular,而且我对它很新。我想在视图中显示一些数据,而数据来自服务器,我知道它是异步的所以我一直试图在视图渲染之前使用resolve来获取数据,但是我无法在组件中获取它,这是我做了什么。

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();
}

}

服务:

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());
}

和我的组成部分:

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

我需要将数据放入materias var中,但我在console.log中得到的只是:

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

1 个答案:

答案 0 :(得分:1)

这里有一些问题。

首先,您要映射来自getTeacherMaters的数据,但您没有返回任何数据,因此很可能会在此处丢失。您需要将其更新为:

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();

其次,您要保存订阅的副本,但我怀疑您要将数据保存到this.materias。由于数据请求是异步的,因此在subscribe块内部之前您将无法获取数据,并且调用subscribe将返回您可以取消的订阅。将您的getMaterias方法更新为:

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