0
我正在學Angular,而且我對它很新。我想在視圖中顯示一些數據,並且數據來自服務器,我知道它是異步的,所以我一直試圖在視圖渲染之前使用解析來獲取數據,但我無法在組件中獲取它,這是我做了什麼。Angular 2和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變種,但所有我在console.log中獲得的是:
Subscriber {closed: false, _parent: null, _parents: null, _subscriptions: Array(1), syncErrorValue: null…}
謝謝你,是的,它是,只是一個愚蠢的錯誤。 –