【发布时间】:2017-05-04 15:05:01
【问题描述】:
我没有得到带有 BehaviorSubject 的组件中的响应值。我得到它并在服务中传递它。
我正在从路由保护服务触发 HTTP。
服务:
@Injectable()
export class ProjectsService {
projects: Subject<Project[]> = new BehaviorSubject<Project[]>([]);
load(clientId: string, active: boolean): Observable<boolean> {
return new Observable<boolean>((obs) => {
this._api.send(active ? 'projects.getActive' : 'projects.getAll',clientId).subscribe(
res => {
let temp = [];
res.forEach(a => temp.push(new Project(a)));
if (active) this.projects.next(temp);
else this.externalProjects.next(temp);
obs.next(true);
obs.complete();
},
err => {
obs.next(false);
obs.complete();
}
);
});
}
组件:
ngOnInit(): void {
// todo: check why not to load already added
this._projectsListener = this._projectsService.projects.subscribe(a => {
this.showIntro = a.length ? false : true;
this.projects = a;
});
}
HTML:
<div class="project" [hidden]="!showIntro" *ngFor="let project of projects>
{{project.title}}
</div>
它只是获取 HTTP 参数的查询参数... 守卫:
@Injectable()
export class ProjectsGuard implements CanActivate {
constructor(
private _projectsService: ProjectsService,
private _router: Router) {}
canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
return this._projectsService.load(next.params['id'], true)
}
}
我也尝试了NgZone,但我不确定它是否正确:
load(clientId: string, active: boolean): Observable<boolean> {
return this._api.send(active ? 'projects.getActive' : 'projects.getAll',clientId)
.map(res => {
let temp = res.map(a => new Project(a));
this._ngZone.run(() => {
console.log('temp: ', temp);
if (active) this.projects.next(temp);
else this.externalProjects.next(temp);
});
return true;
})
.catch(() => Observable.of(false));
}
【问题讨论】:
-
你遇到了什么问题?您可以提及您遇到了什么错误。
-
load()在哪里调用?为什么要使用这么多嵌套的 observables? -
我没有收到错误...只是没有呈现任何数据...无法在组件中获得 HTTP 响应。 load() 在路由保护(canActivate)上被正确调用。