【发布时间】:2019-02-13 03:37:03
【问题描述】:
我一直在努力让解析器为激活的路线工作。我遇到的问题是,在我的路由组件中,我试图从解析器获取的数据始终是未定义的。我知道我的服务有效(我已将值返回到控制台),就在我尝试订阅组件中的路由数据时,没有返回任何内容
这是我的组件
@Component({
selector: 'app-value',
templateUrl: './value.component.html',
styleUrls: ['./value.component.css']
})
export class ValueComponent implements OnInit , OnDestroy {
values: any = {};
newBin: any = [];
navigationSubscription;
bins: Bins;
constructor(private http: Http, private dbService: DbService, private toastr: ToastrService, private router: Router,
private route: ActivatedRoute) {
this.navigationSubscription = this.router.events.subscribe((e: any) => {
if (e instanceof NavigationEnd) {
this.loadLinks();
}
});
}
ngOnInit() {
this.dbService.getBins().subscribe( response => {
this.values = response;
}
);
this.loadLinks();
}
loadLinks() {
this.route.data.subscribe(data => {
this.bins = data['bins'];
console.log(this.bins);
});
}
这是我的app.module 的路线
@NgModule({
declarations: [
AppComponent,
ValueComponent,
],
imports: [
BrowserModule,
HttpModule,
RouterModule.forRoot(
[{path: 'bins', component: ValueComponent, resolve: {bins: LinkResolver}, runGuardsAndResolvers: 'always'},
{path: '', redirectTo: 'bins', pathMatch: 'full' }],
{onSameUrlNavigation: 'reload'}),
这里是解析器
@Injectable({
providedIn: 'root'
})
export class LinkResolver implements Resolve<any> {
constructor(private router: Router, private dbservice: DbService) {}
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<any> {
console.log('in the router');
return this.dbservice.getBins();
}
最后是服务
getBins(): Observable<Bins[]> {
return this.http.get<Bins[]>('http://localhost:5000/api/values');
}
【问题讨论】:
-
您可以订阅并检查您是否从解析器本身获取 getBins 吗??
-
我直接在我的组件中运行了解析器,我能够从我的 API
ngOnInit() { this.dbService.getBins().subscribe( response => { this.values = response; } ); this.linkresolver.resolve().subscribe(res => { this.bins = res; console.log(this.bins); }); }订阅和返回值
标签: angular typescript angular-router angular-resolver