我有这个路由器解析器,用于从Google Firestore检索数据。我正在尝试使用解析器来预先获取数据。当我将调试器放置在resolve函数上时,它将向我显示从服务器检索的数据。但是它永远不会从resolve()方法返回。谁能帮帮我。
路由模块
const routes: Routes = [
{ path: '', component: HomeComponent},
{ path: 'projects', component: ProjectsComponent, resolve: {projectData: ProjectResolver} },
{ path: 'about', component: AboutComponent}
];
应用程序模块
providers: [
ProjectService,
ProjectResolver
],
解析器服务
import { Observable } from 'rxjs';
import { ActivatedRouteSnapshot, RouterStateSnapshot, Resolve } from '@angular/router';
import { Injectable } from '@angular/core';
import { ProjectService } from './project.service';
import { map } from "rxjs/operators";
import { Project } from './project.model';
@Injectable()
export class ProjectResolver implements Resolve<Project[]> {
constructor(private projectService: ProjectService ) {
}
resolve(route: ActivatedRouteSnapshot, router: RouterStateSnapshot) : Observable<Project[]> | any{
return this.projectService.getProjects().pipe(map(project => {
return project //Debugger shows fetched data(Array of projects)
}
));
}
}
项目服务
import { AngularFirestore } from 'angularfire2/firestore';
import { Observable } from "rxjs";
import { Injectable } from "@angular/core";
@Injectable()
export class ProjectService {
constructor(private db: AngularFirestore) {}
getProjects(): Observable<any> {
return this.db.collection('currentProjects').valueChanges();
}
}
**项目组件(此组件从未由Resolver加载 )**
import { Component, OnInit, Injectable } from '@angular/core';
import { Project } from './project.model';
import { ActivatedRoute } from '@angular/router';
import { ProjectService } from './project.service';
import { Observable } from 'rxjs';
@Component({
selector: 'app-projects',
templateUrl: './projects.component.html',
styleUrls: ['./projects.component.css']
})
export class ProjectsComponent implements OnInit {
projects: Project[] = [];
constructor(private route: ActivatedRoute, private projectService: ProjectService) {
}
ngOnInit() {
this.route.data.subscribe((data: Project[]) => {
this.projects = data['projectData'];
})
}
}
答案 0 :(得分:5)
问题是Angular Firebase Observable(事件流)将永远不会像正常的“ observable”那样完成,因此它永远都无法解决。我使用“ take”运算符修改了Observable,以获取第一项并被迫完成。
this.db.collection('currentProjects').valueChanges().take(1);
更改:
我在下面发布了针对我的问题的解决方案:
项目解析器(正在运行)
export class ProjectResolver implements Resolve<any> {
constructor(private db: AngularFirestore) {
}
resolve(route: ActivatedRouteSnapshot, router: RouterStateSnapshot) : any{
return Observable.from(this.db.collection('currentProjects').valueChanges()
.do(data => {
return data
}).take(1))
}
}
项目组件(正在运行)
export class ProjectsComponent implements OnInit {
private projects: Project[];
constructor(private route: ActivatedRoute) {
}
ngOnInit() {
this.route.data.subscribe((data) => {
this.projects = data['projectData'];
})
}
}
答案 1 :(得分:0)
获取诸如this.route.snapshot.data
之类的数据,而不是this.route.data
且无需订阅
ngOnInit() {
this.projects = this.route.snapshot.data['projectData'];
}